
[英]Is it possible to cast an object as 2 different things within the same method?
[英]Is it possible to cast a method?
晚上好,
我只是问自己,是否可以铸造一种方法。
public class A{
public void A_method() {
System.out.println("THIS is A Class --> A_method");
}
}
public class B extends A{
@Override
public void A_method() {
System.out.println("THIS is B Class --> A_method");
}
}
public class Main {
public static void main(String[] args){
A a = new A();
a.A_method();
}
}
Output:“这是一个 Class --> A_method”。
我试着像这样投射它:
((B)a.A_method());
它应该打印:这是 B Class --> A_method
但它不工作。 是否可以转换这样的方法?
谢谢
无法转换方法,转换仅适用于类型(对象和基元)。
如果要调用在子类B
中覆盖的方法,则需要使调用该方法的 object 的类型为B
:
A a = new B(); // the declaration type can be A but the object is a B
或者
B b = new B();
没有其他办法:只要运行时类型不是B
,它就永远不会调用B
中覆盖的方法。 这就是多态性的工作原理。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.