gpt4 book ai didi

java - Java 中私有(private)字段的可访问性

转载 作者:行者123 更新时间:2023-12-01 16:55:06 24 4
gpt4 key购买 nike

我知道如果做成一个类的实例变量private那么它就不能被对象直接访问。

但是在下面的代码中,发生了这样的事情,并且代码运行良好!

怎么样b可以直接获取长度、宽度和高度吗?

public class Box {
private int length,breadth,height;
Box(int a,int b,int c){
length=a;
breadth=b;
height=c;
}
Box(Box b){
length=b.length; //These lines!
breadth=b.breadth;
height=b.height;
}
int volume(){
return length*breadth*height;
}
}

public class BoxWeight extends Box{
public int weight;
BoxWeight(int a,int b,int c,int d){
super(a,b,c);
weight=d;
}
BoxWeight(BoxWeight b){
super(b);
weight=b.weight;
}
}
class apples
{
public static void main(String[] args)
{
BoxWeight mybox1=new BoxWeight(10,20,30,40);
BoxWeight clone=new BoxWeight(mybox1);
System.out.println(mybox1.volume()+"...."+mybox1.weight);
System.out.println(clone.volume()+"...."+clone.weight);
}
}

最佳答案

因为参数的类型相同。在java中,一个对象可以访问同一类型的其他对象的私有(private)成员。因此,在这种情况下,Box 可以访问 Box 类的任何私有(private)成员,即使在不同的对象中也是如此。

关于java - Java 中私有(private)字段的可访问性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34221012/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com