"It will not compile" is listed as a correct answer.
Why exactly the code will not compile?
The method Book#add(Object) does not override ArrayList<Book>#add, that's right. It overloads it, which is perfectly fine.
About Question enthuware.ocpjp.v7.2.1305 :
Moderators: Site Manager, fjwalraven
-
- Posts: 3
- Joined: Wed Sep 24, 2014 7:04 am
- Contact:
-
- Site Admin
- Posts: 10046
- Joined: Fri Sep 10, 2010 9:26 pm
- Contact:
Re: About Question enthuware.ocpjp.v7.2.1305 :
All generic related information is eliminated in the compiled code. So typing ArrayList to Book in BookList doesn't mean BookList now has add(Book ) method. The compiled code of BookList still has add(Object ) method that it inherits from ArrayList.
So, when you try to add add(Object ) method in BookList, the compiler thinks that you are overriding the same add(Object ) method and complains that it violates the BookList class because it is typed to Book and not Object.
So, when you try to add add(Object ) method in BookList, the compiler thinks that you are overriding the same add(Object ) method and complains that it violates the BookList class because it is typed to Book and not Object.
If you like our products and services, please help us by posting your review here.
-
- Posts: 3
- Joined: Wed Sep 24, 2014 7:04 am
- Contact:
Re: About Question enthuware.ocpjp.v7.2.1305 :
Got it after I tried to compile the code.
Compiler actually does not think that BookList#add overrides ArrayList#add, it knows that it doesn't and complains about these methods having the same type erasure (which is why this is not overloading):
Test.java:7: error: name clash: add(Object) in BookList and add(E) in ArrayList
have the same erasure, yet neither overrides the other
public boolean add(Object o){
^
where E is a type-variable:
E extends Object declared in class ArrayList
1 error
I think it would be helpful to correct the explanation in ETS somehow to include the point about the same erasure.
Compiler actually does not think that BookList#add overrides ArrayList#add, it knows that it doesn't and complains about these methods having the same type erasure (which is why this is not overloading):
Test.java:7: error: name clash: add(Object) in BookList and add(E) in ArrayList
have the same erasure, yet neither overrides the other
public boolean add(Object o){
^
where E is a type-variable:
E extends Object declared in class ArrayList
1 error
I think it would be helpful to correct the explanation in ETS somehow to include the point about the same erasure.
-
- Site Admin
- Posts: 10046
- Joined: Fri Sep 10, 2010 9:26 pm
- Contact:
Re: About Question enthuware.ocpjp.v7.2.1305 :
Yes, we will add it to the explanation.
thank you for your feedback!
thank you for your feedback!
If you like our products and services, please help us by posting your review here.
Who is online
Users browsing this forum: No registered users and 43 guests