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
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
and
and you run
it will print testA
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
No comments:
Post a Comment