Multiple choice

What is the output of the following Java program?

class A { A() { System.out.println("Constructor A"); } public void func() { System.out.println("Member function A"); } } class B extends A { B() { System.out.println("Constructor B"); } public void func() { System.out.println("Member function B"); } } public class Hello { public static void main(String args[]) { B b=new B(); b.func(); } }

  1. Constructor A Constructor B Member function B

  2. Constructor B Constructor A Member function B

  3. Constructor A Constructor B Member function A

  4. Constructor B Constructor A Member function A

  5. None of the above

Reveal answer Fill a bubble to check yourself
A Correct answer
Explanation

Whenever we create object for child class, the constructor of parent class is invoked first. Then the child class constructors are invovled. This is because some of the fields in child class derived from parent class remain unintialized, when we invoke directly the constructor of child class. Hence parent class constructor is invoked first rather and constructor of child class is invoked later. b.func(); imvokes child class func() because of method overriding. Hence only child class func() method is invoked but not the func() method in parent class. Hence the ouput will be: Constructor A Constructor B Member function B