Interface (two methods, different return types depending on class) Java

前端 未结 4 1190
甜味超标
甜味超标 2021-01-18 17:49

Any class that extends an interface must implement the methods declared in the interface. Not sure if this is possible but what I want to do is the following :



        
4条回答
  •  醉梦人生
    2021-01-18 18:54

    You can do this with generics, but it's not enforced at runtime. You should also be using implements to implement an interface in a class, rather than extends.

    interface Test {
       T get();
    }
    
    class A implements Test {
        int val;
    
        A(int x) {
            val = x;
        }
    
        @Override
        Integer get() {
           return Val;
        } 
    
    }
    
    class B implements Test {
        String val;
    
        B(String x) {
           val = x;
        }
    
        @Override
        String get() {
            return Val;
        }
    }
    

    Generics only apply to classes, so you're forced to use Integer rather than int as the return type.

提交回复
热议问题