显式类型在java中将子类对象转换为超类 [英] Explicit Type Conversion of sub class object to super class in java
问题描述
考虑下面的代码:
public class Test {
public static void main(String str []){
B b = new B();
A a1 =(A)b; //显式类型转换
A a2 = b;
}
}
class A {}
class B extends A {}
在上面的代码中有两行:
A a1 =(A)b;显式类型转换
A a2 = b;
等效?如果不,那么两者之间的差异和是之间是否有需要将子类对象显式转换为超类对象
如果你这样做
pre> A a1 =(A)b;
您仍然可以
B b2 =(B)A;
将参考转换回B类型。
注意:对象不以任何方式改变,总是 B
有没有在你需要它的情况下?
你只需要一个upcast是在方法选择。
void method(Object o){}
void method(String s){}
method(hello); // calls method(String)
method((Object)hello); //调用方法(Object)
Consider below code:
public class Test{
public static void main(String str[]){
B b = new B();
A a1 = (A)b;//Explicit type conversion
A a2 = b;
}
}
class A{}
class B extends A{}
In the above code are the two line:
A a1 = (A)b;//Explicit type conversion
A a2 = b;
Equivalent? If not then what is the difference between the two and if yes then is there any scenario in java where we need to explicitly convert a sub class object into a super class object?
The explicit type casting of the reference, not the object) is redundant and some IDEs will suggest you drop it.
If you do
A a1 = (A)b;
You can still do
B b2 = (B) A;
to cast the reference back to type of B.
Note: the object is not altered in any way and is always a B
there is no scenario in java where you would need it?
The only time you need an upcast is in method selection.
void method(Object o) { }
void method(String s) { }
method("hello"); // calls method(String)
method((Object) "hello"); // calls method(Object)
这篇关于显式类型在java中将子类对象转换为超类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!