【发布时间】:2014-05-06 16:30:32
【问题描述】:
我有:
public class Circle {
//private instance variable
private double radius = 1;//Declaring "1" as the default value
private String color = "red";//Declaring "red" as the default color and as a string.
// default constructor w/out an argument
public Circle() {
}
public Circle(double r){ //constructor that uses double argument which is assigned to radius
radius = r;
color = "red";
}
//public method "getRadius"
public double getRadius() {
return radius;
}
//public method "getArea", used to get the area of the circle.
public double getArea() {
//method returns the Area of a circle using the below formula
return Math.PI * radius * radius;
}
}
和
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("*****************************************");
我也试图让“红色”圆圈的颜色也打印出来。现在最重要的是我的代码中有以下内容,她说他们是另一种方式。
//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;
}
}
仅供参考....我问她是否应该这样做 System.out.println("红色"); 她说不。
【问题讨论】:
-
如果你没有设置器也没有默认值,那么使用无参数构造函数有什么用?
-
如果你想打破一切,请使用反射。
-
@n1234 哦不,反射不! :P
-
@LuiggiMendoza 哦,是的! :P