Base class hijacks an interface(Thinking in java(英文版)700)

 Base class hijacks an interface(page 700)

Suppose you have a Pet class that is Comparable to other Pet objects:
 
  
  
  
  
  1. public class ComparablePet implements Comparable<ComparablePet>{ 
  2.  
  3.     @Override 
  4.     public int compareTo(ComparablePet arg) { 
  5.         return 0
  6.     } 

It makes sense to try to narrow the type that a subclass of ComparablePet 
can be compared to.For example,a Cat should only be Comparable with other Cats:
 
  
  
  
  
  1. /*The interface Comparable cannot be implemented  
  2. more than once with different arguments:  
  3. Comparable<ComparablePet> and Comparable<Cat>   */ 
  4. //{CompileTimeError} (won't compile) 
  5.  
  6. class Cat extends ComparablePet implements Comparable<Cat>{ 
  7.  
  8.     @Override 
  9.     public int compareTo(Cat arg) { 
  10.         return 0
  11.     } 
  12.      
Unfortunately,this won't work.Once the ComparablePet argument is established for Comparable,no other implementing
class can ever be compared to anything but a ComparablePet:
 
 
  
  
  
  
  1. class RestrictedComparablePets extends ComparablePet  
  2. implements Comparable<ComparablePet> { 
  3.     @Override 
  4.     public int compareTo(ComparablePet arg) { 
  5.         return 0
  6.     } 
  7.  
  8.  
  9. class Gecko extends ComparablePet{ 
  10.     @Override 
  11.     public int compareTo(ComparablePet arg) { 
  12.         return 0
  13.     } 
 
Hamster shows that it is possible to reimplement the same interface that is in ComparablePet,as long as it is exactly the
same,including the parameter types.However,this is the same as just overriding the methods in the base class,as seen in Gecko.
 
下面的代码证明了接口可以重复implements,不过在第二次implements的时候不强求重写方法,重写当然没有问题
  
  
  
  
  1. class TestInterface implements Comparable{ 
  2.  
  3.     @Override 
  4.     public int compareTo(Object o) { 
  5.         // TODO Auto-generated method stub 
  6.         return 0
  7.     } 
  8.      
  9. public class reimplementInterface extends TestInterface implements Comparable{ 
  10.  
 测试类 ComparablePet的作用:
直接实现 Comparable的类的对象可以跟任何对象做比较
 
  
  
  
  
  1. class ComparableDirect implements Comparable{ 
  2.  
  3.     @Override 
  4.     public int compareTo(Object o) { 
  5.         // TODO Auto-generated method stub 
  6.         return 0
  7.     } 
  8.  
  9. public class Test{ 
  10.     public static void main(String args[]){ 
  11.         new ComparableDirect().compareTo(new String("")); 
  12.     } 
继承了ComparablePet的类的对象只能跟同样继承了ComparablePet接口的对象做比较:
  
  
  
  
  1. class ComparableIndirect extends ComparablePet{ 
  2.  
  3. public class Test2{ 
  4.     public static void main(String args[]){ 
  5.         new ComparableIndirect().compareTo(new ComparableIndirect()); 
  6.     } 
 

你可能感兴趣的:(java,in,interface,Tinking)