Page 1 of 1
About Question enthuware.ocajp.i.v7.2.1349 :
Posted: Sun Nov 24, 2013 5:56 pm
by javaman
The correct answer for this question says
"The constructor can take the same type as a parameter."
How can a constructor accept a type of it's own as a parameter? Can't figure out how such a constructor should be called without getting in a chicken-egg situation:
class A{
A(A arg){
}
}
class Test{
public static void main(String[] args){
new A(new A(...)); //'...' should be an instance of A which contains an instance of A etc
}
}
Marc
Re: About Question enthuware.ocajp.i.v7.2.1349 :
Posted: Sun Nov 24, 2013 6:25 pm
by admin
You could have a class that also has a default constructor:
Code: Select all
class A{
A(){
}
A(A arg){
}
}
class Test{
new A(new A());
}
}
HTH,
Paul.
Re: About Question enthuware.ocajp.i.v7.2.1349 :
Posted: Mon Nov 25, 2013 10:44 am
by javaman
Oooh.. of course, I see now. Thanks
Re: About Question enthuware.ocajp.i.v7.2.1349 :
Posted: Wed May 14, 2014 12:28 pm
by JeramieH
Code: Select all
A constructor cannot be final, static or abstract.
Since it seems like constructors are essentially final anyway, why is marking them final an error? Redundant perhaps... but in other places in Java, redundant flags are just ignored. I've read through
Why constructors cannot be final but although there's lots of explanation for why it's not useful, there's no real explanation for why it's an outright error. It doesn't seem to be logically contradictory like static and abstract would be for constructors.
Re: About Question enthuware.ocajp.i.v7.2.1349 :
Posted: Wed May 14, 2014 9:16 pm
by admin
Just the way language designers designed it. I think it makes sense to flag an error because final implies that a constructor can be overridden. This is different from ignoring redundant flags such as static from a field in an interface because the field really is static and so if you put static it is not wrong. Constructor is not "non-final" or "final".
HTH,
Paul.
Re: About Question enthuware.ocajp.i.v7.2.1349 :
Posted: Mon Aug 25, 2014 9:20 am
by MaartenVanLier
You could also call it with null:
Or have a subclass B that extends A and use an instance of B as a parameter: