Variables in Java do not follow polymorphism. Overriding is only applicable to methods but not to variables. In Java, if the child and parent class both have a variable with the same name, Child class’s variable hides the parent class’s variable, even if their types are different. This concept is known as Variable Hiding. In the case of method overriding, overriding methods completely replace the inherited methods but in variable hiding, the child class hides the inherited variables instead of replacing them which basically means that the object of Child class contains both variables but Child’s variable hides Parent’s variable.
Hence when we try to access the variable within Child class, it will be accessed from the child class. If we are trying to access the variable outside of the Parent and Child class, then the instance variable is chosen from the reference type.
Example
Java
// Java Program Illustrating Instance variables // Can not be Overridden // Class 1 // Parent class // Helper class class Parent { // Declaring instance variable by name `a` int a = 10 ; public void print() { System.out.println( "inside B superclass" ); } } // Class 2 // Child class // Helper class class Child extends Parent { // Hiding Parent class's variable `a` by defining a // variable in child class with same name. int a = 20 ; // Method defined inside child class public void print() { // Print statement System.out.println( "inside C subclass" ); } } // Main class public class GFG { // Main driver method public static void main(String[] args) { // Creating a Parent class object // Reference Parent Parent obj = new Child(); // Calling print() method over object created obj.print(); // Printing superclass variable value 10 System.out.println(obj.a); // Creating a Child class object // Reference Child Child obj2 = new Child(); // Printing childclass variable value 20 System.out.println(obj2.a); } } |
inside C subclass 10 20
Conclusion:
Variables in Java do not follow polymorphism and overriding. If we are trying to access the variable outside of Parent and Child class, then the instance variable is chosen from the reference type.