Reputation: 579
public class HelloWorld
{
protected int num = 12;
public void callme()
{
System.out.print(this.num);
}
public static void main(String[] args)
{
HelloWorld myObject1 = new HelloWorld();
myObject1.callme();
OtherClass myObject2 = new OtherClass();
myObject2.callme();
}
}
public class OtherClass extends HelloWorld
{
protected int num = 14;
}
Why the output is "1212" instead of "1214"? In php its "1214" but not viceversa in java. What's the logic behind that?
Upvotes: 1
Views: 612
Reputation: 393781
callme()
method is defined only in the base class, and therefore return this.num;
returns the instance variable of the base class.
There is no overriding of instance variables in Java.
If you'd override that method in the sub-class, by adding
public void callme()
{
System.out.print(this.num);
}
to OtherClass
, myObject2.callme();
will return 14, since it will execute callme()
method of the sub-class, and therefore access the sub-class instance variable.
Upvotes: 3