-1

I have been trying to practise some java mcqs and cant get this one CAN ANYONE EXPLAIN HOW OUTPUT IS -

Class A
Class B
Class C

and not

Class A
Class B
class A
{
    String s = "Class A";
}
 
class B extends A
{
    String s = "Class B";
 
    {
        System.out.println(super.s);
    }
}
 
class C extends B
{
    String s = "Class C";
 
    {
        System.out.println(super.s);
    }
}
 
public class MainClass
{
    public static void main(String[] args)
    {
        C c = new C();
 
        System.out.println(c.s);
    }
}
Federico klez Culloca
  • 26,308
  • 17
  • 56
  • 95

2 Answers2

3

From: https://docs.oracle.com/javase/tutorial/java/javaOO/initial.html https://docs.oracle.com/javase/tutorial/java/IandI/super.html

A super-class constructor is always run before the actual constructor of the instance. If there is no explicit call to super(), compiler automatically inserts it. Initializer block is "copied" inside the actual constructor.

So C c = new C(); would print: "Class A Class B", but there is a subsequent line: System.out.println(c.s); which prints "Class C"

Peter Lang
  • 357
  • 1
  • 5
1

First we should know that:

"When there is a hierarchy of inheritance, and we create an instance of a child, Parents from the top of the hierarchy get initialized, one after each other (so we get objects created from parents implicitly)."

So here the order of class objects are getting created from, by calling new on class C constructor

C c = new C();

, would be: A ---> B ---> C


Here you've put the println statements in blocks. When an object is getting created from a class, blocks get called before the constructor of the Class get executed. In your code, this would be block in class B

And finally with last line of your code System.out.println(c.s);, you've printed the value of s attribute of object c

Hooman
  • 114
  • 1
  • 1
  • 12