title: Java: Why the need to type cast for instanceof() in equals()? Is it for reference or less code?
body: <p>Java newbie here, I have a basic question that is half answered by previous responses in other threads or the docs, but I still don't fully understand the mechanism and I want to be sure I covers the fundamentals (code at bottom, questions in middle).</p>
  
  <p>Basically, I'm overriding the equals() method to check if two MyDate objects have the same date. I do an instanceof check if the o object is a MyDate object, then you type cast a temp object specifically to a MyDate object <code>o</code>, then you compare dates.  <strong>Why do you type cast the temp variable to MyDate class of o, when it already is of the MyDate class?</strong> </p>
  
  <ol>
  <li>Do you use temp variable as an easier reference the object you want to run the equals() comparison? Because you use equals() as comparing <code>MyDate.equals(MyOtherDate)</code>, in the code if I don't designate a variable to hold the reference then you get various errors (temp cannot be resolved as a variable, type mismatch, etc basically the compiler isn't sure where to look unless you write a bunch more code).</li>
  </ol>
  
  <p>2a. Some of the other threads said something to the effect that while instanceof checks if an instance is from a class, it checks the <strong>base</strong> class, but doesn't check a subclass. You do the typecasting because you're specifically telling the compiler to check for that specific object (type casting from a general object to a specific object). NOTE: This might be a version and flavor specific type question, I've seen different replies to similar questions. </p>
  
  <p>2b. Casting changes the reference, not the object itself. So, if the objects are from the same class, but different subclasses, wouldn't it fail at runtime, instead of compile time. And wouldn't I get a ClassCastException?  </p>
  
  <pre><code>public boolean equals(Object o) {
              if (o instanceof MyDate) {
                  MyDate temp = (MyDate) o;
                  if ((temp.day == day) &amp;&amp; (temp.month == month) &amp;&amp; (temp.year == year)) {
                      return true;
                  }
              } 
              return false;
          }
  </code></pre>