View RSS Feed

My Java Tips

Method shadowing (Inheritance)

Rate this Entry
by , 11-09-2011 at 05:50 PM (578 Views)
Method shadowing is a term used for situations, when child and parent classes have methods with exactly same signature. This situation can create problems that sometimes become difficult to understand.



Method shadowing can be done on purpose or by mistake.

Consider the example below:

Java Code:
public class Car {

     	public void startCar()
	{
		System.out.println("Car class - Car started");
	}

	public void stopCar()
	{
		System.out.println("Car class - Car stopped");
	}

        public void turnOnSpecialFeatures()
        {
               System.out.println("Car class - Special features are now running.");
        }

}

public class Mazda extends Car {

        public void turnOnSpecialFeatures()
       {
                System.out.println("Mazda class - Special features are now running.");
       }

}

Public class MainClass {

	public static void main(String[] args) {
		Mazda obj = new Mazda();
		obj.startCar();
		obj.turnOnSpecialFeatures();
		obj.stopCar();

	}

}
Output:


Car class - Car started
Mazda class - Special features are now running.
Car class - Car stopped

Method named turnOnSpecialFeatures exists in class Car and also in class Mazda. The output suggests that the turnOnSpecialFeatures method defined in class Mazda has executed. Actually, methods in child class get preference over methods defined in the parent class. When a method is called, Java compiler searches for the method in the child class. If not found, then the method is searched in the parent class.

Now suppose, we really want to call the method turnOnSpecialFeatures of the parent class. For that we will add the following method in the Mazda class.

Java Code:
public void turnOnSpecialFeaturesCar()
{
     super.turnOnSpecialFeatures();
}
Now when we call turnOnSpecialFeatureCar method, turnOnSpecialFeatures of Car class will be called.

Itís a little thing but can cause problems that are hard to understand.

Happy coding.

Submit "Method shadowing (Inheritance)" to Facebook Submit "Method shadowing (Inheritance)" to Digg Submit "Method shadowing (Inheritance)" to del.icio.us Submit "Method shadowing (Inheritance)" to StumbleUpon Submit "Method shadowing (Inheritance)" to Google

Tags: None Add / Edit Tags
Categories
Java SE

Comments