简体   繁体   中英

Relating Constructor of Super Class in java

If I create an object of a sub-class with no constructors, then I know that the compiler will implicitly provide a default constructor. What if I create a constructor in the sub-class and try to access the super class constructor using the super keyword, and, now, the super class has no constructor in it. Will the compiler provide a default constructor for the super class as well?

是的,如果没有指定的构造函数,则始终有默认的空构造函数

Does the compiler provides a default constructor for the super class also???

The default constructor will be there whether or not there is a subclass that needs it. The default is supplied when the parent is compiled, not later.

...What if I created sub class Constructor and trying to access the super class constructor using the super keyword,and the super class has no constructor in it.

But it does : The default one.

It goes like this.

Lets speak about Object which is the supermost class in java, If you open an editor and just make a class, then it is presumed that It is extending Object. Every class in Java extends from Object. If you do not write your own constructor then Compiler will provide one.

But if you write your own constructor let's say a constructor with one argument, compiler will not provide you with any constructor.

Now lets say taht you extend the above class, then compiler will complain you saying that the superclass does not have a default constructor rather a custom constructor so you need to make one constructor for this child class since first constructor which is called starts from the supermost class that is OBJECT and then proceeds down the line.

Hope this answers comprehensively, Thanks.

Yes the super always occurs even if you didnt explicit declare

   public class FatherTest {

   }


public class SonTest extends FatherTest{

public SonTest(String sonName){
    super(); // this will always occurs

    }

}

If you don't write a constructor for a class, the compiler will implicitly add an empty one for you.

That means this:

public class X {
}

is identical to this:

public class X {
    public X() {
        // there's also an implicit super(); added here, but that's not directly relevant
    }
}

If the super class doesn't have explicit constructor, then an implicit default constructor will be added to it. So your super() will invoke that.

If the super class only have some constructors with parameters. Then super() in the sub-class won't compile. You have to explicitly use one of the defined super-class constructor super(param1, param2, ...) , since super() will be called if you don't call it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM