Page 1 of 1
Re: About Question enthuware.ocpjp.v7.2.1305 :
Posted: Mon May 13, 2013 1:14 am
by renatumb
This question left me a little bit confused...
If every class extends Object and I can OVERLOAD the equals like below:
Code: Select all
public boolean equals (SomeClass x) { ... }
Why can't I OVERLOAD add of ArrayList ?
Also,
The overridden method can use a subclass for the parameters but not a superclass.
How come ?
For me, the overriding method can vary like this:
Code: Select all
<SubClassOrSameClass> methodX (AlwaysSameType var ) throws <SomeSub/UncheckedExceptionOrNothing>
Re: About Question enthuware.ocpjp.v7.2.1305 :
Posted: Sun Jul 21, 2013 3:11 pm
by Deleted User 621
I think the explanation is deficient. The compiler prints:
Code: Select all
BookList.java:8: 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
That is, overriding is not possible, because the two methods have the same erasure. Note that the compiler replaces E with Object in the bytecode, because in generic ArrayList it's typed as "E extends Object". But because the compiler knows at compile-time that E really is Book, as intended by the programmer, this is NOT a valid override, because that would have to use the exact same type. For the same reasons associated with generics, the compiler cannot consider this an overload, because it would result in the same bytecode method.
This is my interpretation. Please correct, if anybody knows better. I believe the last sentence of the explanation "the overridden method can use a subclass for the parameters but not a superclass" is just plain wrong, like renatumb implied. Overriding is covariant for the return type but not for the parameters.
BTW I find this an extremely difficult question, if not the most difficult I encountered

Re: About Question enthuware.ocpjp.v7.2.1305 :
Posted: Sun Jul 21, 2013 4:06 pm
by admin
You are right about the explanation being wrong about overriding. If the subclass uses a different class type for the parameter (whether subclass or superclass), it will not be overriding the base class's method. It will be a new method altogether.
This has now been fixed.
thank you for your feedback!
Paul.