我想做这样的事情:
我有:
A
(泛型类),可能为空。类
A
的具体实现:A1
、A2
、A2
。
现在有一个驱动程序,我有一个通用方法:
Class Driver()
doSomething(A a)
{
a.setVal1();
a.setVal2();
.....
etc.
}
main()
{
A a;
if(user_input == "a1")
a= new A1()
//Intention is, I should be able to access all the variables and methods of A1 & A(if any)
else if(user_input == "a2")
a= new A2()
//Intention is, I should be able to access all the variables and methods of A2 & A(if any)
doSomething(a);
}
}
现在,这里的a
可以是a= new A1
或a= new A2
(在运行时决定)。
如何在 Java 中实现此功能?
注意:类a1
(或a2
)可能有自己的变量(和/或方法),我不想将它们放在类A
中。
任何指示/帮助将不胜感激。
最佳答案
请记住,当您将方法的签名声明为 doSomething(A a)
时,您将能够使用引用 a
仅调用 A
中定义的方法或其父类(super class)(如果可访问)中的方法。
但是,在调用特定于该子类的方法之前,可以将强制转换 a
到其子类之一的对象。在这种情况下,建议使用instanceof
。
例如:
doSomething(A a) {
if (a instanceof A1) {
A1 a1 = (A1) a;
a1.methodSpecificToA1();
} else if (a instanceof A2) {
A2 a2 = (A2) a;
a2.methodSpecificToA2();
}
}
关于java - OOM中如何设计这个案例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17911979/