I understood that this is a reference to the currently executing object. If that is the case can you explain the behaviour of the following code?
public class Inherit {
public static class ClassA
{
private String privateInstanceVar = "Private";
public void classAMethod()
{
System.out.println("In class: " + this.getClass().getName());
System.out.println("Can access: " + this.privateInstanceVar);
}
}
public static class ClassB extends ClassA
{
}
public static void main(String[] args)
{
ClassB b = new ClassB();
b.classAMethod();
//Outputs:
//In class: Inherit$ClassB
//Can access: Private
//System.out.println(b.privateInstanceVar); // Fails to compile
}
}
The first line of classAMethod reports that this is a reference to ClassB. However, on the next line I use this to access the private instance variable privateInstanceVar of ClassA, which I shouldn’t have access to. (The commented out last line of main shows that this is indeed the case.)
So, my questions are:
- If
thisreally is a reference toClassB, how can I access the private instance variable onClassAfrom a method that belongs toClassB? - Is
classAMethodactually a member ofClassAandClassBat the point of execution? - If the answer to 2. is yes, what are the rules for determining in which context any given line in the method will execute?
- If the answer to 2. is no, then what alternative explanation is there for the behaviour of the code?
- Is there some bigger picture or subtlety here that I’m failing to appreciate?
Because you inherit the method from classA, and that method accesses the private variable.
Yes
Compile-time context: the method or field that is visible from the code you are writing will be chosen. Example:
new ClassB().getFoo()will return “bar”, not “phleem”, because ClassA does not know about ClassB.