• Register
0 votes
73 views

Problem :

I have the below two classes

public class A {

    A() {

        System.out.println("A");

    }

}


class B extends A {

    B() {

        System.out.println("B");

    }

}

And after that running

1

A c = new B();

or

2

B c = new B();

It will always give

A

B

Why is this happening to my code? At a first glance, in either of the scenario, I would assume that only a B constructor would be called and so the only output would be

B

But this is completely wrong.

by (3.9k points)

Please log in or register to answer this question.

1 Answer

0 votes

Solution :

With super(), a superclass no-argument constructor is called and with super(parameter list), a superclass constructor with the matching parameter list is called.

If a super class does not have the no-argument constructor then you will get the compile-time error. Object does have such the constructor, so if Object is a only superclass then there is no problem.

If the subclass constructor invokes the constructor of its superclass, either explicitly or implicitly, you might think that there will be the whole chain of the constructors called, all the way back to a constructor of Object. In fact, this is a case. It is called the constructor chaining, and you must be aware of it when there is such long line of class descent.

by (38.6k points)

Related questions

0 votes
0 answers
+1 vote
1 answer
0 votes
1 answer
24 views asked Sep 23, 2020 by jagruthi (680 points)
0 votes
1 answer
0 votes
1 answer
12 views asked Dec 5, 2020 by Mashhoodch (5.6k points)
...