Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Confused with Constructors and Subclasses

I'm having trouble understanding the concept of using constructors with subclasses.

Here is the parent class:

public class A
{
    public A()
    {
        System.out.println("The default constructor of A is invoked");
    }
}

The child class:

public class B extends A
{
    public B(String s)
    {
        System.out.println(s);
    }
}

And my main method:

public class C
{
    public static void main (String[] args)
    {
        B b = new B("The constructor of B is invoked");
    }
}

When I run C, the output I get is

The default constructor of A is invoked

The constructor of B is invoked

What I don't understand is why the message from class A is getting output. Because you pass in a string argument to the constructor of the B class, shouldn't it just print out s? In other words, shouldn't the output simply be:

The constructor of B is invoked

Thanks in advance, I really appreciate any help you guys can give.

like image 653
zaynv Avatar asked Jun 26 '26 21:06

zaynv


1 Answers

From the docs

If a constructor does not explicitly invoke a superclass constructor, the Java compiler automatically inserts a call to the no-argument constructor of the superclass. If the super class does not have a no-argument constructor, you will get a compile-time error. Object does have such a constructor, so if Object is the only superclass, there is no problem.

So even though you've not explicitly called the super class constructor, the compiler inserts a statement called super() in the constructor of class B.

This is how the class B constructor would look post compilation.

public B(String s){
    super(); // this is inserted by the compiler, if you hadn't done it yourself.
    System.out.println(s);
}
like image 133
Rahul Avatar answered Jun 29 '26 10:06

Rahul



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!