Variables in Java Do Not Follow Polymorphism and Overriding
Last Updated :
23 Sep, 2021
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
class Parent {
int a = 10 ;
public void print()
{
System.out.println( "inside B superclass" );
}
}
class Child extends Parent {
int a = 20 ;
public void print()
{
System.out.println( "inside C subclass" );
}
}
public class GFG {
public static void main(String[] args)
{
Parent obj = new Child();
obj.print();
System.out.println(obj.a);
Child obj2 = new Child();
System.out.println(obj2.a);
}
}
|
Output
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.
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...