About Question enthuware.ocajp.i.v7.2.1349 :
Moderator: admin
-
- Posts: 33
- Joined: Wed Nov 13, 2013 4:11 pm
- Contact:
About Question enthuware.ocajp.i.v7.2.1349 :
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
"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
-
- Site Admin
- Posts: 10045
- Joined: Fri Sep 10, 2010 9:26 pm
- Contact:
Re: About Question enthuware.ocajp.i.v7.2.1349 :
You could have a class that also has a default constructor:
HTH,
Paul.
Code: Select all
class A{
A(){
}
A(A arg){
}
}
class Test{
new A(new A());
}
}
Paul.
If you like our products and services, please help us by posting your review here.
-
- Posts: 33
- Joined: Wed Nov 13, 2013 4:11 pm
- Contact:
Re: About Question enthuware.ocajp.i.v7.2.1349 :
Oooh.. of course, I see now. Thanks
-
- Posts: 22
- Joined: Wed Jan 08, 2014 11:24 am
- Contact:
Re: About Question enthuware.ocajp.i.v7.2.1349 :
Code: Select all
A constructor cannot be final, static or abstract.
-
- Site Admin
- Posts: 10045
- Joined: Fri Sep 10, 2010 9:26 pm
- Contact:
Re: About Question enthuware.ocajp.i.v7.2.1349 :
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.
HTH,
Paul.
If you like our products and services, please help us by posting your review here.
-
- Posts: 1
- Joined: Mon Aug 25, 2014 9:15 am
- Contact:
Re: About Question enthuware.ocajp.i.v7.2.1349 :
You could also call it with null:
Or have a subclass B that extends A and use an instance of B as a parameter:
Code: Select all
new A(null);
Code: Select all
new A(new B());
Who is online
Users browsing this forum: No registered users and 66 guests