相对于类变量,上转换和下转换之间有什么区别 [英] What is the difference between up-casting and down-casting with respect to class variable
问题描述
相对于类变量,上转换和下转换之间有什么区别?
What is the difference between up-casting and down-casting with respect to class variable?
例如,在以下程序类中,Animal只包含一个方法,类包含两个方法,那么我们如何将Dog变量转换为动态变量。
For example in the following program class Animal contains only one method but Dog class contains two methods, then how we cast the Dog variable to the Animal Variable.
如果转换完成,那么我们如何使用Animal的变量来调用Dog的另一个方法。 / p>
If casting is done then how can we call the Dog's another method with Animal's variable.
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`();
}
}
推荐答案
- 正在转换为超类型,而向下转换正在转换为子类型。超级强制总是允许的,但是subcasting涉及一个类型检查,并且可以抛出 ClassCastException
。
Up-casting is casting to a supertype, while downcasting is casting to a subtype. Supercasting is always allowed, but subcasting involves a type check and can throw a ClassCastException
.
从 Dog
转换为动物
是一个upcast,因为 Dog
is-a Animal
。一般来说,每当两个类之间存在一个关系时,你就可以上传。
In your case, a cast from from Dog
to an Animal
is a upcast, because a Dog
is-a Animal
. In general, you can upcast whenever there is an is-a relationship between two classes.
向下转换会是这样:
Animal animal = new Dog();
Dog castedDog = (Dog) animal;
基本上你所做的是告诉程序你知道对象的运行时类型真的是。程序会做转换,但仍然会做一个健全检查,以确保它的可能。在这种情况下,转换是可能的,因为在运行时动物
实际上是狗
,即使静态类型动物
是动物
。
Basically what you're doing is telling the program that you know what the runtime type of the object really is. The program will do the conversion, but will still do a sanity check to make sure that it's possible. In this case, the cast is possible because at runtime animal
is actually a Dog
even though the static type of animal
is Animal
.
this:
Animal animal = new Animal();
Dog dog = (Dog) animal;
你会得到一个 ClassCastException
。之所以是因为 animal
的运行时类型是 Animal
,因此当你告诉运行时执行cast它看到动物
不是一个真正的狗
,因此抛出一个 ClassCastException
。
You'd get a ClassCastException
. The reason why is because animal
's runtime type is Animal
, and so when you tell the runtime to perform the cast it sees that animal
isn't really a Dog
and so throws a ClassCastException
.
要调用超类的方法,您可以执行 super.method()
upcast。
To call a superclass's method you can do super.method()
or be performing the upcast.
要调用子类的方法,你必须做一个向下转换,冒险 ClassCastException
。
To call a subclass's method you have to do a downcast and risk the ClassCastException
.
这篇关于相对于类变量,上转换和下转换之间有什么区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!