About Question com.enthuware.ets.scjp.v6.2.95 :
Posted: Mon Nov 21, 2011 2:32 pm
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?
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?