简体   繁体   中英

Calling no-argument constructor in superclass implicitly

This is taken from : http://docs.oracle.com/javase/tutorial/java/IandI/super.html

Note: 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.

I made this small example to test that :

class P as superclass (its empty class):

package org.standro.com.pk1;


public class P {
}

and class N in different package , class N extends class P without explicilty calling super() :

import org.standro.com.pk1.P;


public class N extends P {

    public N() {
        //imlicitly super() is called here .. that means the constructor of P 

    }

    public static void main(String[] arg){
    N n=new N();

    }
}

and no compile error.. Im using JDK1.7 whats wrong with this example and why I don't get error ?

I think the bold sentence above should be :

If the super class does not have a any constructor,....

because if there is at least one constructor .. compiler will get error..

or please if anyone has explanation ..

thanks

Since the class P extends object, and has no constructor, it's constructor defaults to the no argument constructor which implicitly invokes the constructor in Object.

To cause an error, you need to add a parameter to P's constructor like this:

public class P {

    public P(int a) {
    }
}

Now N tried to implicitly call super() which looks for a no-args constructor in P. However, since we added a constructor in P, the default no-args constructor can no longer be used.

Claification:

If there is no constructor, default no-arg one is added. If there is a constructor of any kind, the default no-arg constructor is not added

As per your explanation only, if subclass is not calling super class constructor then automatically compiler inserts an internal call to super class's no arg constrcutor.

so in class N ,you have N() constructor and its internally calling P class no arg constructor.

and P internally calls Object class no arg constructor.

so your code will compile successfully.

if there is no corresponding constructor in super class then only it complains.

so try to put some parameterized constrcutor in base class P(like p(int x){ }) and run your program. you will surely get error because of no arg costrcutor is not available in super class.

Note : no arg constrcutor is inserted only if there is no constrcutor at all in the class.

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