2013-04-28 39 views
-2

我仍然是Java中的新手。我的问题可能是非常基本的。定义为Private的变量

我有一个类的超类箱,

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是框超类的子类:

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不是abl e访问它。我知道我可以将Private改为default/public,但是还有另一种方式,以便传递值的类实际上可以访问它?

PS:由于我是新的我的术语可能是错误的,我的问题很愚蠢

+1

基本上,你会想要使用getters和setter;公共方法来获取或修改您的私有变量。 – 2013-04-28 17:34:11

+0

http://stackoverflow.com/questions/2036970/tutorial-on-getters-and-setters – 2013-04-28 17:34:18

+0

你需要回答的第一个问题是,如果DemoBoxWeight能够访问高度和重量,或者是那些太接近实现细节应该隐藏其他类吗?如果它们应该可用,那么'public int getHeight()'会使高度可读。 – 2013-04-28 17:36:57

回答

5

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

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

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

您可以删除如果你不希望课堂以外的价值改变,你可以使用setter。

+0

我同意,但如果编辑代码并初始化私有变量的高度和深度,说= 1,然后在我创建BoxWeight对象时,在类DemoBoxWeight中,我可以覆盖已经初始化为1的值的高度和深度,无论我是什么通过说3,4,尽管他们受到保护,他们得到设置没有getter/setter – prabh 2013-04-28 17:51:17

+0

@prabh我不知道我明白这个问题。在'DemoBoxWeight'中,你用你提供的构造函数初始化一个'BoxWeight'实例。创建对象'DemoBoxWeight'后,不能再更改这些值。如果您不想在构建对象时更改初始值,请不要提供启用该对象的构造函数。 – MAV 2013-04-28 17:56:59

1

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

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

+0

我同意,但如果编辑代码并初始化私有变量的高度和深度,说= 1,然后在我创建BoxWeight对象时,在类DemoBoxWeight中,我可以覆盖已经初始化为1的值的高度和深度,无论我是什么通过说3,4,尽管他们受保护,他们得到设置没有getter/setter – prabh 2013-04-28 17:58:13

0

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

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

的想法是,(而不是把事情公开),每当在未来你想改变你的箱子的内部表示,你可以做到这一点,而不依赖于高度打扰用户。

例如:

比方说,你想存储对角线,而不是深度。或者你可能想使用浮点数或其他数字类型。

getHeight可能会开始寻找,因为这:

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

而且没有人会了。您还应该阅读约encapsulationinformation hiding

+0

我同意,但如果编辑代码并初始化私有变量的高度和深度,说= 1,然后在类DemoBoxWeight时,我创建BoxWeight对象,我可以覆盖已经初始化为1的值的高度和深度,无论我传递的是3,4,尽管它们受到保护,但它们没有getter/setter – prabh 2013-04-28 17:59:45

0

将私人更改为受保护。

受保护的修饰符允许类层次结构中的所有子类访问实例变量,而无需使用getter或setter方法。

它仍然拒绝访问它的其他类(在类层次结构之外),所以封装仍然占据。