Polymorphism java 8

Asked by At

i know how it works here

Polymorphism does not include instance fields. Methods yes, fields no. Baap b is a reference of type Baap when accessing fields (b.h). When accessing methods, b morphs into a Beta type (b.getH()).

class Baap
{
  public int h = 4;
  public int getH()
  {
    System.out.println("Baap "+h);
    return h;
  }
}
public class Beta extends Baap
{
  public int h = 44;
  public int getH()
  {
    System.out.println("Beta "+h);
    return h;
  }
  public static void main(String[] args)
  {
    Baap betaInBaap = new Beta();
    System.out.println(betaInBaap.h+" "+betaInBaap.getH());
    Beta castedBeta = (Beta) betaInBaap;
    System.out.println(castedBeta.h+" "+castedBeta.getH());
  }
}

enter image description here

What I don't understand is the order of output

As Here o/p must be 4(calling b.h) followed by Beta 44(calling method b.geth()) and the method returns 44 as well so the first line must be 4 Beta 44 44

1 Answers

0
Stultuske On Best Solutions
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.