简体   繁体   中英

Confused with this simple example of polymorphism

Please have a look at this code :

class Foo {
    public int a;
    public Foo() {
        a = 3;
    }
    public void addFive() {
        a += 5;
    }
    public int getA() {
        System.out.println("we are here in base class!");
        return  a;
    }
}

public class Polymorphism extends Foo{
    public int a;
    public Poylmorphism() {
        a = 5;
    }
    public void addFive() {
        System.out.println("we are here !" + a);
        a += 5;
    }
    public int getA() {
        System.out.println("we are here in sub class!");
        return  a;
    }

    public static void main(String [] main) {
        Foo f = new Polymorphism();
        f.addFive();
        System.out.println(f.getA());
        System.out.println(f.a);
    }
}

Here we assign reference of object of class Polymorphism to variable of type Foo , classic polmorphism. Now we call method addFive which has been overridden in class Polymorphism . Then we print the variable value from a getter method which also has been overridden in class Polymorphism. So we get answer as 10. But when public variable a is SOP'ed we get answer 3!!

How did this happen? Even though reference variable type was Foo but it was referring to object of Polymorphism class. So why did accessing fa not result into value of a in the class Polymorphism getting printed? Please help

You're hiding the a of Polymorphism - you should actually get a compiler warning for that. Therefore those are two distinct a fields. In contrast to methods fields cannot be virtual. Good practice is not to have public fields at all, but only methods for mutating private state (encapsulation).

If you want to make it virtual, you need to make it as a property with accessor methods (eg what you have: getA ).

This is due to the fact that you can't override class varibles. When accessing a class variable, type of the reference, rather than the type of the object, is what decides what you will get.

If you remove the redeclaration of a in the subclass, then I assume that behaviour will be more as expected.

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