Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/328.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java中私有字段的可访问性_Java_Inheritance - Fatal编程技术网

Java中私有字段的可访问性

Java中私有字段的可访问性,java,inheritance,Java,Inheritance,我知道,如果一个类的实例变量被设置为私有的,那么对象就不能直接访问它 但是在下面的代码中,这样的事情正在发生,并且代码运行良好 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){

我知道,如果一个类的实例变量被设置为私有的,那么对象就不能直接访问它

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

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中,对象可以访问相同类型的其他对象的私有成员。因此,在这种情况下,
Box
可以访问
Box
类的任何私有成员,即使是在不同的对象中。

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

private
意味着字段(或内部类或方法)在类外不可见(对于任何其他类型都是如此)。但是,由于
b
是同一类型的
Box
,此限制不适用。

private
意味着字段(或内部类或方法)在类之外不可见(对于任何其他类型都是如此)。但是,由于
b
属于同一类型的
Box
,因此该限制不适用。

私有
对于其他类别是不可访问的
b
也是
Box
类型,所以它在自己的家里

Private
对于其他类是不可访问的
b
也是
Box
类型,所以它在自己的家里

简单地说,一个Box对象可以访问Box类内部的Box的privates

简单地说,一个Box对象可以访问Box类内部的Box的privates

访问级别修饰符确定其他类是否可以使用特定字段或调用特定方法“我知道,如果一个类的实例变量是私有的,那么它就不会被对象直接访问。”你这么说是什么意思?你的问题很不清楚(而且似乎有比你需要演示问题更多的代码).访问级别修饰符确定其他类是否可以使用特定字段或调用特定方法“我知道,如果类的实例变量是私有的,那么它就不会被对象直接访问。”这是什么意思?你的问题很不清楚(并且似乎有比您需要演示问题更多的代码)。