WHAT'S NEW?

Overriding

When a sub class and super class have methods with same   signature,always sub class method is invoked, this process is known as " Overriding " .

Overriding takes place only when inheritance occurs.

Consider the following classes

Car.java (Super Class)

public class Car
{
public void start()
{
System.out.println("start of Car");
}
public void stop()
{
System.out.println("stop of Car");
}

public void horn()
{
System.out.println("Horn of Car");
}
}



HondaCity.java (Sub Class)

public class HondaCity extends Car
{
public void start()
{
System.out.println("start of Honda City");
}
public void stop()
{
System.out.println("stop of Honda City");
}

public void brakes()
{
System.out.println("Brakes of Honda City");
}
}


Now let us try to call the methods..

Demo.java

class Demo 
{
public static void main(String[] args) 
{
HondaCity city=new HondaCity();
city.start();
city.horn();
city.brakes();
city.stop();

}
}


Output will be : 

---------- Run ----------
start of Honda City
Horn of Car
Brakes of Honda City
stop of Honda City


It is simple to assume that i called the method of HondaCity and it got executed.

Have a look on following image



Now the picture will become clear.

The image depict the memory structure of HondaCity object. As it is subclass of Car, all the methods of Car comes down (shown in blue part is memory inherited of Car) to the HondaCity and hence when you call city.start() or city.stop(), compiler has two methods of start() and stop() and hence start() and stop() of HondaCity is invoked as per the process of Overriding.

Hope this image make you understand the process of overriding.

Point to remember while working with overriding.

1. When a method is defined a private, it does not get inherited and if in that case sub class have method with same signature, it will be considered as mere coincidence and not as overridden method.

2. If it a requirement that when you call the sub class method first the super class method should get invoke in that case following snippet will help. 

public void start()
{
super.start();
System.out.println("Start of Honda City");
}

3. Signature of the method consist of access specifier, return type, method name and parameters.



0 comments:

Post a Comment