这里内部发生了什么? [英] What happened internally here?
问题描述
class A
{
int i=10;
void show()
{
System.out.println("show()");
}
}
class B extends A
{
int j=20;
void show1()
{
System.out.println("show1()");
}
public static void main(String ar[])
{
A a1=new B();//What happened internally here.please give me answer.
a1.show();
a1.show1();
}
}
推荐答案
A a1=new B();//What happened internally here.please give me answer.
a1.show();
a1.show1();
发生的事情是你创建了 B的实例
并为 A
类型的变量分配了引用。没关系,因为 B
实例是 A
。
What happened is that you created an instance of B
and assigned the reference to an variable of type A
. That's OK, because a B
instance is a A
.
在下一行中,您在 B
实例上调用了一个 A
方法。没关系。
In the next line you called one of the A
methods on the B
instance. That's OK.
在最后一行中,您尝试调用 B
方法。但由于静态类型 a1
是 A
,导致编译错误。但是,如果您编写了以下内容,它将编译并运行正常。
In the last line you attempted to call a B
method. But since the static type of a1
is A
that results in a compilation error. However, if you had written the following, it would have compiled and run just fine.
((B) a1).show1();
如果这不能回答你的问题,请改写它,以便我们更好地理解它。
If this doesn't answer your question, please rephrase it so that we can understand it better.
这篇关于这里内部发生了什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!