简体   繁体   中英

Is there anyway in JAVA to execute Sub Class's Constructor before the Super Class's Constructor?

class Super
{
    Super()
    {
        System.out.println("This is Super Constructor");
    }
}
class Sub extends Super
{
    Sub()
    {
        //super() is automatically added by the compiler here!
        System.out.println("This is Sub Constructor");
        //super(); I can't define it here coz it needs to be the first statement!
    }
}
class Test
{
    public static void main(String...args)
    {
        Sub s2=new Sub();
    }
}  

Output :
This is Super Constructor
This is Sub Constructor

Anyway to do so?
Or you can't access Sub() before Super()?
I know Super Class or Inherited Classes are initialized first then the sub classes, just doing this for learning purposes only!

In a constructor, the compiler will always add a call to super() for you if you didn't provide this call by yourself.

If you look with a decompiler, your Sub constructor will look like this:

Sub()
{
    super();
    System.out.println("This is Sub Constructor");
}

So no, it is not possible.

It will always call base class constructor ( parent ) first and then the initiating class ( child ). In your case super() will execute first.

good read: Which executed first, The parent or the child constructor?

As other answers say not possible. Not sure why you are trying to do this but better rethink your implementation, as you always would want to make sure inherited field are initialised first as child class implementation could depend on it.

As said, the super constructor is always called. Maybe you should rewrite your questions and explain, why you need that.

Heres a simple answer. The concept of Inheritance is about the IS-A relationship. So technically, Dog class is a child of Animal Class . . . upon creating the object, Dog class is first an ANIMAL before it becomes classified as a DOG

... hope this clearifies things . . so its not possible to do it the way you asked

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