
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Field 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 subclass field hides the superclass’s field irrespective of the types. This mechanism is known as field 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
Still, if you need to access the fields of superclass you need to use the super keyword as −
Example
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); System.out.println("Name: "+super.name); System.out.println("age: "+super.age); } } public class FieldHiding{ public static void main(String args[]){ new Sub().display(); } }
Output
Name: Vishnu age: 22 Name: Krishna age: 25