具有多个接口的类

时间:2015-09-17 20:08:24

标签: java oop inheritance

我有两个接口inter1和inter2以及实现它们的类:

public interface Interface1 {
    method1();
}
public interface Interface2 {
    method2();
}
public class Implementer implements Interface1, Interface2 {
    method1() { 
         // something 
    }
    method2() { 
         // something 
    } 
}
public class Test { 
    public static void main(String[] args) {
        Interface1 obj = quest();
        obj.method1();
        if(obj instanceof Interface2) {
            obj.method2(); //exception
        }    
    }

    public static Interface1 quest() {
        return new cl();
    }
}

如何将obj转换为Interface2并调用method2(),或者可以在不进行转换的情况下调用method2()?

3 个答案:

答案 0 :(得分:3)

如果您撰写inter1 obj = ...,则除非您转为obj.method2)inter2类型,否则您将无法撰写implements inter2

例如

inter1 obj = quest();
if (obj instanceof class1)
    ((class1) obj).method2();

inter1 obj = quest();
if (obj instanceof inter2)
    ((inter2) obj).method2();

顺便说一句,当您使用Java编写时,通常会给出以大写字母开头的类和接口名称,否则会让读取代码的人感到困惑。

答案 1 :(得分:1)

使用genecics可以声明实现多种类型的通用引用。您可以从它实现的每个接口调用方法而无需强制转换。示例如下:

public class TestTwoTypes{

    public static void main(String[] args) {
        testTwoTypes();
    }

    static <T extends Type1 & Type2> void testTwoTypes(){
        T twoTypes = createTwoTypesImplementation();
        twoTypes.method1();
        twoTypes.method2();
    }

    static <T extends Type1 & Type2> T createTwoTypesImplementation(){
        return (T) new Type1AndType2Implementation();
    }
}

interface Type1{

    void method1();
}

interface Type2{
    void method2();
}

class Type1AndType2Implementation implements Type1, Type2{

    @Override
    public void method1() {
        System.out.println("method1");
    }

    @Override
    public void method2() {
        System.out.println("method2");
    }
}

输出结果为:

method1
method2

答案 2 :(得分:0)

如果你想在春天这样做,一般的想法是:

// Test.java
public class Test {
    private final Interface1 i1;
    private final Interface2 i2;
    public Test(Interface1 i1, Interface2 i2) {
        this.i1 = i1;
        this.i2 = i2;
    }
}

<!-- application-context.xml -->
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
    <bean id="implementer" class="org.mypackage.Implementer" />
    <bean id="test" class="org.mypackage.Test">
        <constructor-arg ref="implementer"/>
        <constructor-arg ref="implementer"/>
    </bean>
</beans>

// Main.java
public static void main(String[] args) {
    ApplicationContext context = new ClassPathXmlApplicationContext("application-context.xml");
    Test t = (Test) context.getBean("test");
}