简体   繁体   中英

Class extending another issue?

I am learning Java and I am puzzled here: How exactly does this code work?

class A
{
    int n = 9;

    void show()
    {
        System.out.println(n);
    }
}

class B extends A 
{
    void show()
    {
        System.out.println(n+" "+super.n+" "+a.n);
    }

    int n = 4;
    static A a = new A();

    public static void main(String[] args)
    {
        B b = new B();
        a.show();//9, expected
        a = b;
        /*Line A*/ a.show();//4 9 9
        /*Line B*/ b.show();//4 9 9
    }
}

In Line A the function from B will be called, this is expected. But why does it print 4 9 9?

You put b in a but the b always stays a B Class -object in background.

You can print.out it like this:

/*Line B*/ b.show();//4 9 9
System.out.println(a.getClass());

The reference is from type A but the object on heap is the same b object.

In line

a = b;

the static variable a is set to an instance of class B . This is possible because B inherits from A .

As a result, line a calls method show() from class B , not A .

For more info, search for material on Polymorphism .

In Line A, we are actually calling method .show() on a reference of type class A . Here class B is a subclass of class A . In Java a parent class reference can point to a subclass object.

when the JVM sees this call, it actually inspects the object the reference is actually pointing to. In our case it is pointing to a subclass object of type class B . Here, show method is also declared in class B . Which means, it is successfully overriding the parent method. When JVM sees this it actually calls the subclass method instead of the parent class one. This whole process is called as polymorphism .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM