I\'m following this MOOC on OOP in Java and it has presented an example I don\'t fully understand. In the example, a Book
class has been created and they are const
Casting a variable to a data type basically is telling the compiler "Trust me, I know what I'm doing." In the case of casting an "Object" to "Book", you are assuring the compiler that the object is, in fact, a Book and to proceed accordingly. It also as the effect of forcing you to believe you know what you are doing.
Edit: I'm not sure if you are asking why you needed the actual cast (adding "(Book)") or why you needed to make the assignment to a Book variable. I answered the former. If the question is the latter, the answer is you need the Book variable so the Book methods are available.
Since you have the tools to make the determination, you would think that the cast is not necessary since the compiler is capable of generating the same code you use to make the determination, requiring you to just make the assignment:
Book book = object; // Wrong
instead of
Book book = (Book) object; // Right
If you expect the compiler to "just know" that the Object is a Book, then the compiler will have to test the Object each time you use a Book method. By explicitly telling it in the assignment, the compiler can create code specific to the Book class without any further examination of the Object.
Because the compiler cannot (is forbidden to) infer that your previous type check was done for the purpose of eliminating improper object types before casting.
E.g., sometimes less is more: what if in the next statements you only need to cast your object to one of the base classes or implemented interfaces?
interface Authored {
public getAuthorName();
}
interface Publication {
public String getISBN();
};
public class Book
implements Authored, Publication {
// ...
public boolean equals(Object other) {
if (other == null) {
return false;
}
if (getClass() != other.getClass()) {
return false;
}
// on purpose, we use only the Publication interface
// because we want to avoid potential misspelling or missing
// title, author name, etc. impacting on equality check
// We'll consider ISBN as a key unique enough to
// determine if two books (e.g. registered in different
// libraries) are the same
Publication p=(Publication)other;
return this.getISBN().equals(p.getISBN());
}
}
after
if (getClass() != object.getClass()) {
return false;
}
you can be sure your object is a book, but java still does not know it
so you can savely tell it to try the casting with
Book compared = (Book) object;
You have to cast your Object
-type object to Book
, because you want to use getPublishingYear()
and getName()
functions which are specific to the Book
class. The Object
class does not have such methods.