Java中的基本构造函数用法
问题描述:
无论出于何种原因,我都无法在其他任何地方找到此问题,也无法在线找到答案。如果我具有以下条件:
For whatever reason, I cannot find this question anywhere else, nor can I find the answer online. If I have the following:
package temp1;
public class MainClass {
public static void main(String[] args) {
}
public MainClass(int radius_x, int area_x, int circumference_x) {
int radius = radius_x;
int area = area_x;
int circumference = circumference_x;
}
}
假设这甚至是正确的用法,那么我该如何真正使用这里的构造函数中定义的变量?由于作用域,它们只能在构造函数内部工作。
Assuming that this is even correct usage, then how would I actually use the variables defined in the constructor here? They only work inside of the constructor thanks to scope.
答
您所提供的代码毫无意义,这是正确的。更常见的情况是使用构造函数初始化一些实例变量,然后可以在整个类中使用它们。
You are correct that the code you supply makes little sense. A more common scenario is to use the constructor to initialize a few instance variables, which can then be used throughout the class.
public class MainClass {
private int radius;
private int area;
private int circumference;
public static void main(String[] args) {
}
public MainClass(int radius_x, int area_x, int circumference_x) {
this.radius = radius_x;
this.area = area_x;
this.circumference = circumference_x;
}
}