- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
What is instance variable hiding in Java?
Whenever you inherit a superclass a copy of superclass’s members is created at the subclass and you using its object you can access the superclass members.
If the superclass and the subclass have instance variable of same name, if you access it using the subclass object, the instance variables of the subclass hides the instance variables of the superclass irrespective of the types. This mechanism is known as field hiding or, instance variable hiding.
But, since it makes code complicated field hiding is not recommended.
Example
In the following example we have two classes Super and Sub one extending the other. They both have two fields with same names (name and age).
When we print values of these fields using the object of Sub. The values of the subclass are printed.
class Super { String name = "Krishna"; int age = 25; } class Sub extends Super { String name = "Vishnu"; int age = 22; public void display(){ Sub obj = new Sub(); System.out.println("Name: "+obj.name); System.out.println("age: "+obj.age); } } public class FieldHiding{ public static void main(String args[]){ new Sub().display(); } }
Output
Name: Vishnu age: 22
- Related Articles
- instance variable hiding in Java
- Instance variable in Java
- Instance variable as final in Java
- What is method hiding in Java and how to use it?
- What is method hiding in C#?
- What is variable shadowing in java?
- What is the difference between method hiding and method overriding in Java?
- What is the difference between method overloading and method hiding in Java?
- What is a final variable in java?
- What is JAVA_HOME variable in Java Environment?
- What is Variable Handle in Java 9?
- Explain about field hiding in java?
- What is static blank final variable in Java?
- What is a variable, field, property in Java?
- Instance variables in Java
