What will be printed to console as a result of the following code execution?

public class Test {
    public static void main(String[] s) {
        A a = new B();
        a.b();
    }
}

class A {
    void a() {
        System.out.println("A-a");
    }
    
    void b() {
        System.out.println("A-b");
        a();
    }
}

class B extends A {
    void a() {
        System.out.println("B-a");
    }
    
    void b() {
        System.out.println("B-b");
        super.b();
    }
}
Explanation
An object of class B, which contains overridden methods a() and b(), is created. Therefore, when referring to these methods, their overridden versions will be called. Roughly speaking, the sequence of actions may be described as follows:
01. A a = new B(); // instance of class B is created
02. a.b(); // b() method is called. It is overridden in the current object
// Overridden version is called ("B-b")
03. super.b();  // b() method from superclass is called ("A-b")
04. a(); // a() method is called. It is overridden in the current object.
// Overridden version is called ("B-a")
 

Follow CodeGalaxy

Mobile Beta

Get it on Google Play
Send Feedback
Cosmo
Sign Up Now
or Subscribe for future quizzes