How can I refer to the class type a interface is implementing in Java?

后端 未结 4 1420
一生所求
一生所求 2020-12-05 07:31

I came to a problem with interfaces in a program I\'m making. I want to create a interface which have one of its methods receiving/returning a reference to the type of the o

4条回答
  •  臣服心动
    2020-12-05 08:26

    Java supports covariant return types, so that's one option. Take advantage of the fact that both A and B are derived from Object:

    public interface I {
        Object getSelf();  // or I, see below
    }
    public class A implements I {
        A getSelf() { return this; }
    }
    public class B implements I {
        B getSelf() { return this; }
    }
    

    The point is that both A.getSelf() and B.getSelf() are legitimate overrides of I.getSelf(), even though their return type is different. That's because every A can be treated like an Object, and so the return type is compatible with that of the base function. (This is called "covariance".)

    In fact, since A and B are also known to derive from I, you can replace Object by I for the same reasons.

    Covariance is generally a Good Thing: Someone who has an interface object of type I can call getSelf() and get another interface, and that's all she needs to know. On the other hand, someone who already knows he has an A object can call getSelf() and will actually get another A object back. The additional information can be used to get a more specific derived type, but someone who lacks that information still gets everything that's prescribed by the interface base class:

    I x = new A();
    A y = new A();
    
    I a = x.foo();    // generic
    A b = y.foo();    // we have more information, but b also "is-an" I
    A c = (A)x.foo(); // "cheating" (we know the actual type)
    

提交回复
热议问题