Tuesday, January 8, 2019

Can be call this() and supper() togther in same method and constructure ?

There is a difference between super() and this().
super()- calls the base class constructor whereas
this()- calls current class constructor.
Both this() and super() are constructor calls.
Constructor call must always be the first statement. So we can not have two statements as first statement, hence either we can call super() or we can call this() from the constructor, but not both.
 Example :-
class TempB {
    TempB() // default constructor
    {
        System.out.println("default constructor");
    }

    TempB(int x) // one parameter constructor
    {
        System.out.println("value of x is" + x);
    }
}

class C extends TempA {
    C() // default constructor
    {
        super();
        this(10);
        System.out.println("default constructor");
    }

    C(int x) // one parameter constructor
    {
        this(10, 20);
        System.out.println("value of x is" + x);
    }

    C(int x, int y) // two parameter constructor
    {
        System.out.println("Add result is" + (x + y));
    }

    public static void main(String[] args) {
        new C();
    }


In above example first statement is correct whare use supper() but after use this. It is not correct because it break the contract of calling first statement.
 

No comments:

Post a Comment