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();
}
}
可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
回答1:
A a1=new B();//What happened internally here.please give me answer.
a1.show();
a1.show1();
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
.
In the next line you called one of the A
methods on the B
instance. That's OK.
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.
回答2:
Happened that you shouldn't be able to call:
a1.show1();
because even if a1 instance type is B (new B()), you are treating it like an A object, which hasn't the show1 method defined.