Variables are not overriden in subclasses in Java

Today we will discuss some aspects of inheritance and methods overriding in Java. The general idea of inheritance in Java can be found here. Here are two pieces of code to show some tricky things for newbies:

public class InheritanceTest {
    public static void main(String[] args) {
        Sub s = new Sub();
        Base b = s;
        System.out.println(s.getName());
        System.out.println(b.getName());

        System.out.println(s.name);
        System.out.println(b.name);
    }
}

class Base {
    public String name = "Base";
    public String getName() {
        return name;
    }
}

class Sub extends Base {
    public String name = "Sub";
    public String getName() {
        return name;
    }
}
As expected, getName() method is overridden by Sub class; b variable has the Base type, but still points to the Sub object. So the output is Ok, this is good. But what will last two `printlns` do? The result is: First of all, it's worth saying, that a class variable shadows the inherited variable from it's parent's class. But how did we get the last result? The thing is : variables names in Java are resolved by the reference type, not the object they are referencing. That's why we cannot `override` a variable in the subclass, but only method.

0 comments:

Post a Comment