Click here to Skip to main content
15,867,756 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
The code is as shown below - but I don't get why it gives that weird output.

Java
class Aa {
    Aa() {
        System.out.println("a");
    }

    Aa(String name) {
        System.out.println("a name");
    }
}

class B extends Aa {
    B() {
        this("abc");
        System.out.println("b");
    }

    B(String name) {
        System.out.println("b name");
    }
}

public class A {
    public static void main(String[] args) {
        B b = new B();
    }
}

and the output is:

a
b name
b

What I have tried:

Constructor issue - related to inheritance
Posted
Updated 12-Feb-22 19:44pm
v2
Comments
M Imran Ansari 12-Feb-22 23:54pm    
Which class object you called in Main method?
Richard Deeming 14-Feb-22 10:57am    
If you were expecting the output to start with a name, then you would need to call the correct base-class constructor from B(String name):
B(String name) {
    super(name);
    System.out.println("b name");
}

1 solution

It's doing exactly what you told it to:
It constructs an instance of B which derives from Aa - so the base class constructor is called first, which prints "a".
Then the derived class parameterless constructor is called, which calls the string parameter method which prints "b name", then the constructor prints "b".

If you think about it, that has to happen - the base class constructor has to be called before the derived class constructor or the derived class couldn't rely on anything in the base class being setup and ready before it tries to extend it.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900