• Register
0 votes
56 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.

7 5 2
3,870 points

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.

9 7 4
38,600 points

Related questions

0 votes
0 answers 11 views
0 votes
1 answer 991 views
991 views
Problem : I am currently working on the project and i am getting the error as below : "Implicit super constructor MyPerson() is undefined. Must explicitly invoke another constructor" But I am unable to understand it. Below is my MyPerson class: public class ... and just giving it an instructor variable as below : public class MyStudent extends MyPerson { public MyStudent(String myInstructor) { } }
asked Dec 16, 2019 alecxe 7.5k points
1 vote
1 answer 34 views
34 views
Problem: Hello all, Please explain to me the error in the following program. class test { String name="name"; public person(String nm){name=nm;} } class emp extends test { String empid="0000"; } public class emptest { public static void main( ... class emp extends test required: String found no arguments reason: actual and formal argument lists differ in length Thanks for the effort. Best regards
asked Mar 10 Gavin 15.3k points
0 votes
1 answer 10 views
0 votes
1 answer 40 views
40 views
Problem : I have following two classes: JDialog and JFrame (see signature below). I want them to have few extra methods, but I also want them both to extend my code, without rewriting the code Is it possible to do that? java.awt.Window java.awt.Dialog javax.swing. ... the identical way. So I will not want to write the code twice. I want only one class to utilize the code of the other class.
asked Dec 7, 2019 alecxe 7.5k points