我完全坚持我的业余项目。我有 MySingleton 实现MyInterface
和调用MyMethod()
. MyMethod()
应该将任何一个MySubcls
作为参数。问题是如何在MyMethod()
没有泛型的情况下声明?应该使用许多带有不同参数的声明还是没有泛型就没有办法?
Main.java => 需要从单个方法打印所有子类的值
public class Main{
public static void main(String[] args){
MySubcls01 subCls01 = new MySubcls01();
MySubcls02 subCls02 = new MySubcls02();
MySingleton.INSTANCE.MyMethod(subCls01);
MySingleton.INSTANCE.MyMethod(subCls02);
}
}
enum MySingleton implements MyInterface
{
INSTANCE;
@Override
public void MyMethod();// TODO - need to pass subCls01 or subCls02
{
System.out.println(subCls01.value);
System.out.println(subCls02.value);
}
}
interface MyInterface
{
void MyMethod(); // TODO - what parameter for any subclass???
// void MyMethod(MySubcls01 subCls01);
// void MyMethod(MySubcls02 subCls02); => brute-force approach
// <T> void MyMethod(T type); => shouldn't use generics
}
class MySupercls
{
// some stuff
}
class MySubcls01 extends MySupercls
{
String subValue = "i'm from subclass01";
}
class MySubcls02 extends MySupercls
{
String subValue = "i'm from subclass02";
}