edit : it is not a duplicata : I already know by heart private is accessible within the class only, protected within class and subclasses, and other class within the same packages and public is accessible everywhere, no modifiers = package only. that is not what I am talking about. I am talking about accessing from an object : object.var. Just go read the exemple and try yourself to understand the compiler errors, you can't with just this simple rule.
Before closing the question, make sure you got it, it's not an easy question and if you think so you may have not get the question.
Here is my code and i don't get how object.privateVar and object.protectedVar behaves when calling it from different classes In a daughter A class i can call daughterBObject.protected while in java doc it says we can call object.protectedVar only if the class we are calling in is involved in creating the object.
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
}
}
Can anyone explain these behaves to me?