Re: If the object is an instance of a class, why was it cast?
On Jul 6, 8:51 am, metaperl <metap...@gmail.com> wrote:
re:http://java.sun.com/docs/books/tutorial/java/IandI/objectclass.html
// why cast obj if it is an instance of Book?
// if it is an instance of Book, then it must have the method
available to it,
// either directly in its class or via dispatch to its parent classes
public boolean equals(Object obj) {
if (obj instanceof Book)
return ISBN.equals((Book)obj.getISBN());
else
return false;
}
(Book)obj.getISBN() -- this expression can be rewritten like,
Book tmp = (Book)obj;
tmp.getISBN(); the compiler is very sure that, tmp is an instance of
Book and it has the method getISBN(), so the compilation succeeds.
But, if you dont cast it, and just make the statement like,
obj.getISBN() -- the compiler does not find the getISBN() method in
Object class, and simply blasts. Its doing it's job very well
actually.
Thing is, the poor compiler cannot predict, which object, the
reference can point to, at run time. Thats why you need a cast. But,
this hurdle is removed in Java 1.5. Yes, read about Generics of Java
1.5.
--
Manivannan.Palanichamy (@) Oracle.com
http://mani.gw.googlepages.com/index.html