1
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?

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
Mohammad Sharaf Ali
  • 569
  • 1
  • 4
  • 19

1 Answers1

3

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.

Eran
  • 387,369
  • 54
  • 702
  • 768