变量定义为私有

时间:2013-04-28 17:31:38

标签: java

我仍然是Java的新手。我的问题可能非常基本。

我有一个班级超级班,

package chapter8;

public class Box {

    double width;
    private double height;
    private double depth;

    Box(double w, double h, double d) {
        width = w;
        height = h;
        depth = d;
    }

    double volume() {
        return width * height * depth;
    }
}

BoxWeight是Box超类的子类:

package chapter8;

public class BoxWeight extends Box {

    double weight;

    BoxWeight(double w, double h, double d, double m){
        super(w, h, d);
        weight = m;
    }
}

现在我的主要是DemoBoxWeight

package chapter8;

public class DemoBoxWeight {

    public static void main(String[] args) {

        BoxWeight myBox1 = new BoxWeight(2, 3, 4, 5);

        System.out.println("Volume1 :" + myBox1.volume());
        System.out.println("Weight1 :" + myBox1.weight);
        System.out.println("Widht1: " + myBox1.width);
        System.out.println("Depth1: " + myBox1.depth); // as depth is private, it is not accessible
    }
}

由于高度和深度被定义为Private,因此实际传递这些变量值的DemoBoxWeight无法访问它。我知道我可以将Private更改为default / public但是还有另一种方法,以便传递值的类实际上可以访问它吗?

PS:因为我是新手,我的术语可能是错的,我的问题非常愚蠢

5 个答案:

答案 0 :(得分:5)

这样做的通常方法是编写这样的getter和setter:

public double getHeight()
{
    return this.height;
}

public void setHeight(double height)
{
    this.height = height;
}

如果您不希望从班级外部更改值,则可以删除setter。

答案 1 :(得分:1)

基本上,您需要为类属性提供访问方法。

有两种访问方法 - getterssetters,这些是根据Java Bean definition

为您的班级提供读写权限的标准方法

答案 2 :(得分:1)

以下是有关封装的文档(您正在处理的内容):http://docs.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html

答案 3 :(得分:0)

这主要是通过创建所谓的getters来完成的。

public int getHeight(){
  return this.height;
}

这个想法是(不是公开宣传),无论何时你想改变你的盒子的内部表示,你都可以在不打扰用户的情况下做到这一点。

以示例:

假设你想存储对角线而不是深度。或者您可能想要使用浮点数或其他数字类型。

getHeight可能会开始这样看:

public int getHeight(){
  return diagonalstoHeight(diagonal1, height, width);
}

现在没人会。您还应该阅读encapsulationinformation hiding

答案 4 :(得分:0)

将私人更改为受保护。

protected modifier允许类层次结构中的所有子类访问实例变量,而无需使用getter或setter方法。

它仍然拒绝其他类(在类层次结构之外)访问它,因此仍然会考虑封装。

相关问题