18 May 2015

Hiding Fields in Java with Example

In a subclass if a field has same name as in its super class then sub class field hides the super class's field.

Let's see the behavior of hidden fields with an example.
// Super Class
class A{
   String name = "Super";
}
// Sub Class
class B extends A{
   String name = "Sub";
}
public class Test{
   public static void main(String args[]){
      B obj1 = new B();   // Case 1: Sub class Reference Type
      System.out.println(obj1.name);   // Sub
      A obj2 = new B();   // Case 2: Super class Reference Type
      System.out.println(obj2.name);   // Super
   }
}
Output:
Sub
Super

In the preceding example there is a field 'name' in Class A and there's one more field with same name in Class B which is sub class of Class A. Inside Class B a new field is created instead of overriding the Class A field and thus Class A field got hidden. And, inside main() method at case 1 we are creating a sub class object assigned to sub class (B) reference type which outputs 'Sub', and at case 2 we are creating a sub class object assigned to super class (A) reference type which outputs 'Super'. This concludes that super class field is not overridden and it is hidden which can be accessed by using the of super class reference.

Also, with in sub class the field in the super class can be accessed through super keyword, its syntax is shown below:
super.fieldname;
Note: Hiding fields is a bad practice and not recommended as it makes code difficult to read.





Popular Posts

Write to Us
Name
Email
Message