Thursday, 20 February 2014

Hiding Fields

Within a class, a field that has the same name as a field in the super class hides the super class's field, even if their types are different.

Hiding Static fields
Example
class SuperClass{
 static String data = "I am a string variable";
}

class SubClass extends SuperClass{
 static int data = 10; 
 
 public static void main(String args[]){
  System.out.println(data);
  System.out.println(SuperClass.data);
 }
} 
 
Output
10
I am a string variable

Observe the above program, the variable data is of type String in the super class and type int in the sub class. Even though the types are different, the variable in the sub class hides the variable in the super class.

Hiding instance fields
class SuperClass{
 String data = "I am a string variable";
}
    
class SubClass extends SuperClass{
 int data = 10; 

 void printData(){
  System.out.println(data);
  System.out.println(super.data);
 }

 public static void main(String args[]){
  SubClass obj1 = new SubClass();
  obj1.printData();
 }
} 
   
Output
10
I am a string variable


Usage Of Polymorphism                                                 Super keyword                                                 Home

No comments:

Post a Comment