Friday, 24 May 2013

Can Instance variables be overridden by inheritance in Java?

We know that functions can be overridden by inheritance but are instance variables overridden?
Go through the following code

We have a class called  Superclass which has an instance variable name and an public method printName() to print it.

public class Superclass {
    private String name = "John";
   
    public void printName()
    {
        System.out.println("Name is " + name);
    }
}


Now we write Subclass which extends Superclass. This class also has an instance variable called name and a function with same name(overridden).

public class Subclass extends Superclass {
   
    private String name = "Sam";
   
    public void printName()
    {
        System.out.println("Name is " + name);
    }

}
 

Finally we do the following

Superclass myClass = new Subclass();
        myClass.printName();


and guess what the output is? Even before that is it correct to have variables with same name is super class and subclass.

The answer is Yes!!
The output is : Name is Sam

Explanation

  Simple explanation is only functions are overridden not the variables. When we call  printName() function on myClass object it first check whether the reference type SuperClass has this function. if it is not there Java will throw an exception. Since it is present we can proceed. Now java will find what kind of object this actually is. It will travel down the inheritance tree and call the appropriate function of  Subclass. Since name is Sam in SubClass it is printed.

No comments:

Post a Comment

t> UA-39527780-1 back to top