[英]Possible to declare a method in super class that returns an object of type subclass?
[英]Is there a way of retrieving the type of a subclass, when an object is passed in as type super class?
如果我有方法签名
public void myMethod(SuperClass s){
}
和SuperClass
有三个子类, myMethod
是否有任何方法可以获取传入的子类的类名?
不确定它是否重要,但SuperClass是抽象的。
myMethod中是否有任何方法可以获取传入的子类的类名?
是的,通过使用getClass
方法 :
public void myMethod(SuperClass s){
System.out.println(s.getClass());
}
备注1:
然而,这听起来像是Bad Design™。
无论你想在做myMethod
考虑有在它的方法SuperClass
(提供一个有意义的默认实现,或使其抽象迫使子类实现的方法),并调用此方法s
在你的方法:
public void myMethod(SuperClass s){
s.abstractMethod();
}
备注2:
如果myMethod
的逻辑看起来与SuperClass
的目的无关,并且您不想将myMethod
代码放在此类中,请考虑实现访问者模式 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.