Java练习....需要帮助而不使用getter和setter

时间:2014-05-06 16:30:32

标签: java setter getter

我有:

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("红色&#34); 她说没有。

1 个答案:

答案 0 :(得分:2)

您需要String color课程中Circle属性的获取者,然后使用它,因为您已使用radiusarea

除此之外,我建议您为Circle类中的字段创建setter,以便更改每个实例的属性值。

(因为这是一个家庭作业,所以不会给出代码。)


在奇怪的情况下,您根本不想使用任何getter / setter(这在实际应用程序中确实很奇怪),您可以更改属性的修饰符以直接从其他类访问它们。这是Java修饰符访问级别:

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

因此,您可以将String colorprivate更改为public,任何类都可以访问此属性并使用它或更改其值而不会出现任何问题。请注意,通过这样做,您可以打破班级的encapsulation

更多信息: