Page 1 of 1

About Question com.enthuware.ets.scjp.v6.2.95 :

Posted: Mon Nov 21, 2011 2:32 pm
by ETS User
Consider the following code:
import java.util.*;
class Book{ }
class TextBook extends Book{ }

class BookList extends ArrayList<Book>
{
public int count = 0;
public boolean add(Object o)
{
if(o instanceof Book ) return super.add((Book) o);
else return count++ == -1;
}
}

//in valid context
BookList list = new BookList();
list.add(new Book());
list.add(new TextBook());
list.add("hello");

System.out.println(list.count);

What will it print?

A: It will not compile.
Observer that BookList extends a typed ArrayList, which is typed to Book. Therefore, the add(<E> ) method in ArrayList has been typed to add(Book). Hence, BookList cannot override add(Book) method with add(Object) method. The overridden method can use a subclass for the parameters but not a superclass.
------

I wonder why in this case we consider the 'add(Object o)' method as an overridden one? Why it is not might be overloaded add method? If this assumption true, It will not compile only due to the fact that o is "hello" in 'if(o instanceof Book )' - String has no relation to hierarchy of Book. Where I am wrong?

Re: About Question com.enthuware.ets.scjp.v6.2.95 :

Posted: Tue Nov 22, 2011 2:41 pm
by admin
Think of it this way: All generic information is removed at runtime. So actually, add(<E> ) is same as add(Object) to the JVM. Therefore, you cannot overload add(<E>) with add(Object). It would be considered overriding.

Re: About Question com.enthuware.ets.scjp.v6.2.95 :

Posted: Tue Mar 20, 2012 5:32 am
by J.Andrés
A: It will not compile.
Observer that BookList extends a typed ArrayList, which is typed to Book. Therefore, the add(<E> ) method in ArrayList has been typed to add(Book). Hence, BookList cannot override add(Book) method with add(Object) method. The overridden method can use a subclass for the parameters but not a superclass.

8-) If the method use a subclass for the parameters will not result in a legal overload?

class Book
{}

class ElQuijote extends Book
{}

class MyBookList extends ArrayList<Book>
{

@Override
public boolean add(ElQuijote o)
//Legal overload not a override
{
return super.add(o);
}

}


Really "public boolean add(Object o)" is valid override in runtime , not in compile time. With the type erasure the method will be again "public boolean add(Object o)" , curious at least, no?

I am right?

Re: About Question com.enthuware.ets.scjp.v6.2.95 :

Posted: Tue Mar 20, 2012 11:21 am
by admin
You are right. The statement is misleading and should be fixed.
thank you for your feedback!