In this example, why is it still necessary to typecast an object to be sure of its type, even after getClass() has been called?

前端 未结 4 1067
长发绾君心
长发绾君心 2021-01-28 16:20

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

4条回答
  •  野趣味
    野趣味 (楼主)
    2021-01-28 17:01

    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());
      }
    }
    

提交回复
热议问题