您创建了一个构造函数,但里面的变量只对构造函数本身来说是本地的,而不是在它之外。为此,您需要类成员字段:
public class MainClass {
private int radius;
private int area;
private int circumference;
public static void main(String[] args) throws Exception {
MainClass m = new MainClass(5, 6, 7);
System.out.println("The radius is " + m.getRadius());
}
public MainClass(int radius_x, int area_x, int circumference_x) {
radius = radius_x;
area = area_x;
circumference = circumference_x;
}
public int getRadius() {
return radius;
}
public void setRadius(int radius) {
this.radius = radius;
}
public int getArea() {
return area;
}
public void setArea(int area) {
this.area = area;
}
public int getCircumference() {
return circumference;
}
public void setCircumference(int circumference) {
this.circumference = circumference;
}
}
请记住,也不需要传入area_x
,circumference_x
这些可以派生自radius_x
. 那是假设您忠实于术语的含义,而不是仅仅玩弄变量来学习语言。