0

I would like to make a clarification with regards to multilevel inheritance in Java. Could somebody please explain each examples output (e.g. between option (i) and (iv), would the class of the object be the direct parent above, or the main parent class A)?

i)     A a = new C(); a.P(); will print B.P T/F?
ii)    D d = new B(); d.Q(); will cause a compilation error T/F?
iii)   B b = new C(); b.M(); will cause a compilation error T/F?
iv)    A a = new E(); a.P(); will print A.P T/F?
squirrel
  • 309
  • 2
  • 11
  • 1
    Possible duplicate of [Java : If A extends B and B extends Object, is that multiple inheritance](https://stackoverflow.com/questions/24378375/java-if-a-extends-b-and-b-extends-object-is-that-multiple-inheritance) – Kaustubh Khare Mar 05 '18 at 04:54

2 Answers2

1

I) A a = new C(); a.P(); //will print B.P - correct

  1. C is child of A, so we can put C object to A variable.
  2. A has P() method, so we can call a.P().
  3. C has no it's own P() method, but it was inherited from B, so it will print "B.P". Not from A because it was explicitly overrided.

II) D d = new B(); d.Q(); //will cause a compilation error - correct

  1. B is not child of D, so we can't put B object to D variable.

III) B b = new C(); b.M(); //will cause a compilation error - wrong

  1. C is child of B, so we can put C object to B variable.
  2. B has no it's own M() method, but it was inherited from A, so we can call b.M().
  3. C has overrided M() method, so it will print "C.M".

IV) A a = new E(); a.P(); //will print A.P - correct

  1. E is child of A, so we can put E object to A variable.
  2. A has P() method, so we can call a.P().
  3. E has no it's own P() method, just like D, but it was inherited by chain from A, so it will print "A.P".
Powercoder
  • 695
  • 1
  • 5
  • 25
0

You may be interested in the instanceof operator in Java:

System.out.println("Im a String" instanceof Object);  // prints "True"
Nathan majicvr.com
  • 950
  • 2
  • 11
  • 31