About Question enthuware.ocajp.i.v7.2.1349 :

Help and support on OCA OCP Java Programmer Certification Questions
1Z0-808, 1Z0-809, 1Z0-815, 1Z0-816, 1Z0-817

Moderator: admin

Post Reply
javaman
Posts: 33
Joined: Wed Nov 13, 2013 4:11 pm
Contact:

About Question enthuware.ocajp.i.v7.2.1349 :

Post 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

admin
Site Admin
Posts: 10045
Joined: Fri Sep 10, 2010 9:26 pm
Contact:

Re: About Question enthuware.ocajp.i.v7.2.1349 :

Post 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.
If you like our products and services, please help us by posting your review here.

javaman
Posts: 33
Joined: Wed Nov 13, 2013 4:11 pm
Contact:

Re: About Question enthuware.ocajp.i.v7.2.1349 :

Post by javaman »

Oooh.. of course, I see now. Thanks

JeramieH
Posts: 22
Joined: Wed Jan 08, 2014 11:24 am
Contact:

Re: About Question enthuware.ocajp.i.v7.2.1349 :

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

admin
Site Admin
Posts: 10045
Joined: Fri Sep 10, 2010 9:26 pm
Contact:

Re: About Question enthuware.ocajp.i.v7.2.1349 :

Post 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.
If you like our products and services, please help us by posting your review here.

MaartenVanLier
Posts: 1
Joined: Mon Aug 25, 2014 9:15 am
Contact:

Re: About Question enthuware.ocajp.i.v7.2.1349 :

Post by MaartenVanLier »

You could also call it with null:

Code: Select all

new A(null);
Or have a subclass B that extends A and use an instance of B as a parameter:

Code: Select all

new A(new B());

Post Reply

Who is online

Users browsing this forum: No registered users and 66 guests