0

The below code can't work, I can't get any idea about reason, why is like that? And if I can find a way to invoke constructor in another override's constructor?

Althrough, I know that there can be a solution, put common init code in a class function. So, forgive me for the siny question.

Public AClass extends BClass {
    AClass(Context c) {
       super(c);
       //below has common init code
       //init data and some operations
      // other operations

    }

    AClass(Context c, Attr a) {
       super(c, a);
       this(c)  // error
    }
}

also, below can't work either,

AClass(Context c, Attr a) : this(c) {
   super(c, a);
}

highly appreciated for your kindly help.

gladman
  • 1,208
  • 4
  • 19
  • 39

2 Answers2

3

Depending on what the constructors of BClass do, the following might work:

public AClass extends BClass {
    AClass(Context c) {
        this(c, (Attr) null);
        // below has common init code
        // init data and some operations
        // other operations
    }

    AClass(Context c, Attr a) {
        super(c, a);
    }
}

You can call only one constructor from a constructor. You can not call this (another constructor) and super (the constructor of the super class), and you can not call this or super multiple times. And you can only call those as the first statement of the constructor.

Thomas Mueller
  • 48,905
  • 14
  • 116
  • 132
2

You cannot have both call to the super() (super class constructor) as well as this() (overloaded constructor) in the same definition of a constructor.

In java language specification, you must have call to super class constructor or call to other overloaded constructor as the first line in your constructor definition. Which clearly indicates that you cannot give call to both of them one after another.

Ideally, in such cases you must call overloaded constructor which eventually places a call to super class constructor.

For details refer this stack-overflow link.

Community
  • 1
  • 1
Ankur Shanbhag
  • 7,746
  • 2
  • 28
  • 38