title: Java inheritence: Validating Subclass Type at Compile Time
body: <p>Say, I have a simple class <code>Fruit</code> defined as follows:</p>
  
  <pre><code>public class Fruit {
      int price;
  
      public boolean isEqualPrice(Fruit object) {
          return (object.price == price);         
      }
  }
  </code></pre>
  
  <p>Now, there are several subclasses of <code>Fruit</code> such as <code>Apple</code>, <code>Orange</code>, <code>Mango</code> etc. I want the method <code>isEqualPrice</code> to be valid only when these subclasses are the same. For example, <code>Apple.isEqualPrice(Apple)</code> would be valid, but <code>Apple.isEqualPrice(Orange)</code> would not be. How should I define the parameter of  <code>isEqualPrice</code> to acheive this? I don't want to override <code>isEqualPrice</code> in every subclasses of <code>Fruit</code>.</p>
  
  <p>One possible solution might be:</p>
  
  <pre><code>public boolean isEqualPrice(Fruit object) {
          if(this.getClass() != object.getClass())
              throw new IllegalArgumentException();
          return (object.price == price);         
      }
  </code></pre>
  
  <p>But it will report classes are same or not only at runtime, and an user has no way to realize the correct parameter type watching the method signature. Is there any way to detect this at compile time?</p>
  
  <p><code>NOTE:</code> I think <code>compareTo</code> method of <code>enum</code> is such kind of method, as every <code>enum</code> has this method and a type of <code>enum</code> can't be compared to other type. But I couldn't understand how it is implemented.</p>