Java – confused with constructors and subclasses

I can't understand the concept of using constructors with classes

This is the parent class:

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

Children's class:

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

My main method is:

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

What I don't understand is why messages from Class A are being output Because you pass a string parameter to the constructor of class B, shouldn't it just print out? In other words, the output should not just:

Thank you first. I really appreciate any help you give

Solution

From docs

Therefore, even if you do not explicitly call the superclass constructor, the compiler inserts a statement named super () into the constructor of class B

This is what the class B constructor looks like after compilation

public B(String s){
    super(); // this is inserted by the compiler,if you hadn't done it yourself.
    System.out.println(s);
}
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>