在java中使用Upcasting有什么需要? [英] What's the need to use Upcasting in java?
问题描述
我已经阅读了网上的大部分论文,但我仍然无法理解,为什么我们必须使用预告。
I've gone through most of the papers in the net, but I'm still not able to understand, why we have to use upcasting.
class Animal
{
public void callme()
{
System.out.println("In callme of Animal");
}
}
class Dog extends Animal
{
public void callme()
{
System.out.println("In callme of Dog");
}
public void callme2()
{
System.out.println("In callme2 of Dog");
}
}
public class UseAnimlas
{
public static void main (String [] args)
{
Dog d = new Dog();
Animal a = (Animal)d;
d.callme();
a.callme();
((Dog) a).callme2();
}
}
您可以考虑此示例进行向上转换。在这里使用向上转换有什么用? d
和 a
都提供相同的输出!
You can consider this example for upcasting. What's the use of upcasting here? Both d
and a
giving the same output!
推荐答案
在大多数情况下,明确的上传完全没必要,也没有效果。
In most situations, an explicit upcast is entirely unnecessary and has no effect.
在你的例子中,显式上传
In your example, the explicit upcast
Animal a = (Animal)d;
可以替换为:
Animal a = d; // implicit upcast
隐式upcast(对于Java对象类型)的目的是忘记 静态类型信息,以便具有特定类型的对象可以在需要更通用类型的情况下使用。这会影响编译时类型检查,而不会影响运行时行为。
The purpose of an implicit upcast (for a Java object type) is to "forget" static type information so that an object with a specific type can be used in a situation that requires a more general type. This affects compile-time type checking, not runtime behavior.
(对于基本类型,upcast会导致转换,并且在某些情况下会导致精度损失;例如 long
- > float
。)
(For a primitive type, an upcast results in a conversion, and can in some cases result in loss of precision; e.g. long
-> float
.)
但是,在某些情况下,显式upcast的存在会改变语句/表达式的含义。
However, there are situations where the presence of an explicit upcast changes the meaning of the statement / expression.
其中一种情况在Java中使用upcasting是必要的,当你想强制使用特定的方法覆盖时;例如假设我们有重载方法:
One situation where it is necessary to use upcasting in Java is when you want to force a specific method override to be used; e.g. suppose that we have overloaded methods:
public void doIt(Object o)...
public void doIt(String s)...
如果我有一个字符串,我想调用第一个重载而不是第二,我必须这样做:
If I have a String and I want to call the first overload rather than the second, I have to do this:
String arg = ...
doIt((Object) arg);
相关案例是:
doIt((Object) null);
如果没有类型转换,代码将无法编译。 (我不确定这是否算作上传,但无论如何都是这样。)
where the code won't compile without the type cast. (I'm not sure if this counts as an upcast, but here it is anyway.)
第二种情况涉及varadic参数:
A second situation involves varadic parameters:
public void doIt(Object... args)...
Object[] foo = ...
doIt(foo); // passes foo as the argument array
doIt((Object) foo); // passes new Object[]{foo} as the argument array.
第三种情况是对原始数字类型执行操作;例如
A third situation is when performing operations on primitive numeric types; e.g.
int i1 = ...
int i2 = ...
long res = i1 + i2; // 32 bit signed arithmetic ... might overflow
long res2 = ((long) i1) + i2; // 64 bit signed arithmetic ... won't overflow
这篇关于在java中使用Upcasting有什么需要?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!