【发布时间】:2018-09-11 16:48:11
【问题描述】:
编辑:它不是重复的:我已经知道私有只能在类中访问,在类和子类中受保护,并且同一包中的其他类和公共在任何地方都可以访问,没有修饰符 = 仅包。这不是我要说的。我说的是从一个对象访问:object.var。 只需阅读示例并尝试自己了解编译器错误,仅凭这个简单的规则就无法做到。
在结束问题之前,确保你明白了,这不是一个简单的问题,如果你这么认为,你可能没有得到这个问题。
这是我的代码,我不明白 object.privateVar 和 object.protectedVar 在从不同类调用时的行为方式 在子类 A 中,我可以调用daughterBObject.protected,而在 java 文档中,它说只有当我们调用的类参与创建对象时,我们才能调用 object.protectedVar。
heritage.closefamilly.Mother:
package heritage.closefamilly;
import heritage.faraway.Auntie;
public class Mother {
private int priv;
protected int prot;
public int pub;
public Mother(){
priv = 1;
prot = 5;
pub = 10;
}
public void testInheritance(Mother m, Daughter d, Auntie a){
System.out.println(""+m.priv+m.prot+m.pub);
System.out.println(""+d.priv+d.prot+d.pub); // d.priv compiler error
System.out.println(""+a.priv+a.prot+a.pub);// a.priv compiler error
}
}
heritage.closefamilly.Daughter :
package heritage.closefamilly;
import heritage.faraway.Auntie;
public class Daughter extends Mother{
public void testInheritance(Mother m, Daughter d, Auntie a){
System.out.println(""+m.priv+m.prot+m.pub); // m.priv compiler error
System.out.println(""+d.priv+d.prot+d.pub); // d.priv compiler error why ? we are in daughter class !
System.out.println(""+a.priv+a.prot+a.pub); // a.priv compiler error, why does a.prot compile while we are in daughter class, it doesn't extends auntie neither it is auntie's subclass .. Javadoc says Object.prot shouldn't work when class it is called in is not involed in creating Object
}
}
heritage.faraway.Auntie:
package heritage.faraway;
import heritage.closefamilly.Daughter;
import heritage.closefamilly.Mother;
public class Auntie extends Mother{
public void testInheritance(Mother m, Daughter d, Auntie a){
System.out.println(""+m.priv+m.prot+m.pub);// m.priv & m.prot compiler error
System.out.println(""+d.priv+d.prot+d.pub); // d.priv & d.prot compiler error javadoc says " it is not involved in the implementation of mother and daughter"
System.out.println(""+a.priv+a.prot+a.pub); // a.priv compiler error whY? we are in auntie class
}
}
谁能向我解释这些行为?
【问题讨论】:
-
d.priv-priv变量在 Daughter 类中不是。它在母亲类中 -
关于您的编辑:您的示例的行为与人们期望它们的行为完全相同。我不确定你不明白哪一部分。例如,Mother 有一个私有变量“priv”。女儿无法访问它,因为它是私有的,因此访问 d.priv 将永远无法工作。这是你难以理解的部分吗?
-
例如:a.prot 在 Daughter 类中有效!可女儿不给阿姨送,阿姨也不给女儿送。而且女儿和阿姨不在同一个包裹里……你怎么解释?
标签: java oop inheritance access-modifiers