Polymorphism java 8

public int h = 44;
  public int getH()
  {
    System.out.println("Beta "+h);         // print line 1
    return h;
  }
  public static void main(String[] args)
  {
    Baap b = new Beta();
    System.out.println(b.h+" "+b.getH());  // print line 2
    Beta bb = (Beta) b;
    System.out.println(bb.h+" "+bb.getH()); // print line 3
  }

In your first print statement in your main method, you want it to print b.h+ " "+ b.getH(). It can’t print this, before it knows the value returned by b.getH();

So, it runs b.getH() which prints (seperately) System.out.println("Beta "+h);
before returning a value to the main method. (print line 1)

That explains your first line.
After the value is returned, the main method can now print print line 2, because it now knows what b.getH() has as result:

System.out.println(b.h+" "+b.getH());

This explains your second line in the output.
The same order is executed when running print line 3.

Leave a Comment