Java练习…需要不使用getter和setter的帮助吗
我有: 及 我也在尝试打印出圆圈“红色”的颜色。现在最重要的是我的代码中有以下内容,她说这是另一种方式Java练习…需要不使用getter和setter的帮助吗,java,setter,getter,Java,Setter,Getter,我有: 及 我也在尝试打印出圆圈“红色”的颜色。现在最重要的是我的代码中有以下内容,她说这是另一种方式 public class TestCircle { // Testing function public static void main(String[] args) { Circle c1 = new Circle(); // initialize with default constructor Circle c2 = new Circle(5); // initiali
public class TestCircle {
// Testing function
public static void main(String[] args) {
Circle c1 = new Circle(); // initialize with default constructor
Circle c2 = new Circle(5); // initialize with constructor that takes radius as argument
//prints the results of the program.
System.out.println("*****************************************");
System.out.println("Details of circle 1: ");
System.out.println("Radius: " + c1.getRadius());
System.out.println("Area: " + c1.getArea());
System.out.println("Color: " + color);
System.out.println("*****************************************");
System.out.println("Details of circle 2: ");
System.out.println("Radius: " + c2.getRadius());
System.out.println("Area: " + c2.getArea());
System.out.println("Color: " + c2.getColor());
System.out.println("*****************************************");
仅供参考……我问她我是否应该这样做
系统输出打印项次(“红色”);
她说没有。你需要在
圆
类中为你的字符串颜色属性使用一个getter,然后像你已经在半径
和区域
中做的那样使用它
除此之外,我建议您为Circle
类中的字段创建setter,以便更改每个实例的属性值
(由于这是家庭作业,因此不会给出代码)
在奇怪的情况下,您根本不想使用任何getter/setter(这在实际应用程序中非常奇怪),您可以更改属性的修饰符,以允许直接从其他类访问它们。以下是Java修改器访问级别:
//Constructor that uses a string argument which is assigned to color
public Circle(String c) {
color = C;
}
//public method "getColor", used to get the color of the circle.
public String getColor() {
return color;
}
}
因此,您可以将String color
从private
更改为public
,任何类都可以访问该属性并使用它,或者更改其值,而不会出现任何问题。注意,通过这样做,你打破了你的课堂
更多信息:
如果没有设置器和默认值,使用无参数构造函数有什么用?如果要破坏所有内容,请使用反射。@n1234哦,不,反射不!:P@LuiggiMendoza哦,是的这不是家庭作业。我不在学校。我已经有了计算机科学学士学位。“她”指的是一个朋友。我们都在互相挑战,让自己在编程方面做得更好。我们想成为程序员,拥有基本的知识foundation@LuiggiMendoza你显然不知道答案,这就是为什么你会说这样的话。这只是一个问题,我被困在哪里才是最重要的。我确信当它被计算出来的时候会是一个“哦”的时刻。字符串颜色是私有的,而Circle()中的变量不是(你应该指定它,而不是默认值)。顺便说一下,它应该是。。。私有静态最终字符串COLOR=“红色”
//Constructor that uses a string argument which is assigned to color
public Circle(String c) {
color = C;
}
//public method "getColor", used to get the color of the circle.
public String getColor() {
return color;
}
}
Modifier Class Package Subclass World
public Y Y Y Y
protected Y Y Y N
no modifier Y Y N N
private Y N N N