could somone plz gv me an answer.?
how to use this() and super() together in a constructor code.???
both needs to me the first statement..!
Printable View
could somone plz gv me an answer.?
how to use this() and super() together in a constructor code.???
both needs to me the first statement..!
In constructor either this() or super() should be the first one to get executed.
U can't give both.
My question is why u got the necessity to use both in ur constructor?
Always by default constructor refers the current scope (i.e) this().why u need to call explicitly?
if u implemeted some abstract class u can use super() method
otherwise use "this "
it referes the current class
I'm sorry but this reply is completely wrong. Use of super has nothing to do with abstract classes. It all has to do with whether you want your constructor to first call a specific constructor of the super class or if you wish it to call another constructor of the current class.
I suppose it's possible that if the superclass has a parameterized constructor that isn't called from the default subclass constructor, but the default subclass constructor does some required initialization, a parameterized subclass constructor might want to do both, so it's tempting to think that explicit calls to both are required from the parameterized subclass constructor:An easy solution is to abstract the default subclass initialization into a subclass method that the parameterized subclass constructor can also call.Code:class Super {
private int x;
public Super() {
this(10);
}
public Super(int x) {
this.x = x;
}
}
class Sub extends Super {
private int y;
// default constructor does local init and wants default superclass init
public Sub() {
y = 5;
... // etc.
}
// constructor wants default local init and custom superclass init
public Sub(int x) {
// this() ?? we'd like this too...
super(x);
}
}