Saturday, 19 December 2015

Variables Inheritance in Java

Background

In one of the previous posts we saw method overriding. 
In case of variables it is slightly different. It is shadowing that overriding.

Variables Inheritance in Java

Following code will help you understand better

class A {
    int number = 10;
}

class B extends A {
    int number = 4;

    public void test() {
        System.out.println(this.number);
        System.out.println(super.number);
        System.out.println(((A)this).number); //same behavior as super.number
    }
}

public class HelloWorld {
    
    public static void main(String args[]) {
        B b = new B();
        b.test();
    }

}

And this will output : 
4
10
10

Note : Access to static/instance fields and static methods depend on class of the polymorphic reference variable and not the actual object to which reference point to. Also variables are never overridden. They are shadowed.

So if you have

public class A {
    public static String test = "testA";
    public static void test() {
        System.out.println(test);
    }
}


and

public class B extends A {
    public static String test = "testB";
    public static void test() {
        System.out.println(test);
    }
}


and you run

public class Test {
    public static void main(String args[]) {
        A a  = new B();
        a.test();
    }
}


it will print testA

Note : In method overridden return type can be same or subclass of the super class method. Same goes for Exception thrown. Exception thrown by the overridden method can be same or subclass of Exception thrown by method in the super class. However the access modifies for the overridden method should be more strict.

Related Links

No comments:

Post a Comment

t> UA-39527780-1 back to top