Variables in Java Do Not Follow Polymorphism and Overriding
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.
inside C subclass 10 20
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.