Method overriding is one of the importance concept in Java Programming.
What is Method Overriding?
In Inheritance hierarchy when a child class defines exact same method that is available in parent class then the method is called overridden method.
The process of creating overridden method is called method overriding.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 | class Shape { void draw() { System.out.println("Draw Shape"); } } class Triangle extends Shape { void draw() { System.out.println("Draw Triangle Shape"); } } class Rectangle extends Shape { void draw() { System.out.println("Draw Rectangle Shape"); } } class Circle extends Shape { void draw() { System.out.println("Draw Circle Shape"); } } public class MyClass { public static void main(String args[]) { Shape shape = new Shape(); shape.draw(); Triangle triangle = new Triangle(); triangle.draw(); Rectangle rectangle = new Rectangle(); rectangle.draw(); Circle circle = new Circle(); circle.draw(); } } |
Result
1 2 3 4 | Draw Shape Draw Triangle Shape Draw Rectangle Shape Draw Circle Shape |
We have created a class Shape.
Also created child classes Triangle, Rectangle and Circle.
On child class we have created same method draw()
. Creating exact same method in child is known as method overriding.
In child class method signature and return type is exact same as parent but child class provides new definition to overridden method.
Why method overriding?
When defined method in parent class is not suitable for child class then we override method.
As in above example method draw()
is overridden in all child class.
Because draw() behaves differently for different classes.
Note: If we want to access the
1 2 3 4 | void show() { super.show();//this call’s A’s show(); System.out.println(" Class B "); } |
1 2 3 | Inside display Class A Class B |
Note: Overriding occurs only when the method name and parameter list of the method are identical.
Method with same name and different parameter list are simply overloaded not overridden.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | class A { void show() { System.out.println("Inside Class A show method"); } } class B extends A { void show(int a) { // overload show() System.out.println("Indide class B show method"); } } public class abc { public static void main(String arg[]) { B objB = new B(); objB.show(); // this calls show() of class A objB.show(10); // this calls show() of class B } } |
Result
1 2 | Inside Class A show method Indide class B show method |