What happened internally here?

2020-04-16 02:59发布

问题:

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.



标签: java oop