Java interfaces and return types

后端 未结 3 1839
没有蜡笔的小新
没有蜡笔的小新 2020-12-01 09:00

Consider I have the following interface:

public interface A { public void b(); }

However I want each of the classes that implement it to ha

3条回答
  •  暖寄归人
    2020-12-01 09:59

    Generics.

    public interface A{
        public E b();
    }
    
    public class C implements A{
        public C b(){
            return new C();
        }
    }
    
    public class D implements A{
        public D b(){
            return new D();
        }
    }
    

    Search up generics for more details, but (very) basically, what's happening is that A leaves E's type up to the implementing clases (C and D).

    So basically A doesn't know (and doesn't have to know) what E might be in any given implementation.

提交回复
热议问题