【发布时间】:2010-09-14 09:40:49
【问题描述】:
假设我有接口 MyInterface 和 2 个实现 MyInterface 的类 A、B。
我声明了 2 个对象:MyInterface a = new A() 和 MyInterface b = new B()。
当我尝试传递给函数时 - 函数 doSomething(A a){} 出现错误。
这是我的代码:
public interface MyInterface {}
public class A implements MyInterface{}
public class B implements MyInterface{}
public class Tester {
public static void main(String[] args){
MyInterface a = new A();
MyInterface b = new B();
test(b);
}
public static void test(A a){
System.out.println("A");
}
public static void test(B b){
System.out.println("B");
}
}
我的问题是我从一些可以是各种类的组件接口中获取,我需要为每个类编写函数。
所以一种方法是获取接口并检查它是哪种类型。 (A的实例)
我想知道其他人是如何处理这个问题的??
谢谢
【问题讨论】: