Search code examples
javaconstructorsubclasssuperclasssuper

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!


Solution

  • 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.