Write A Program In Java To Demonstrate Method Overriding.
In this, we will create a java program which demonstrate the use of Method Overriding
Before understanding the program we need to know about the Method Overriding
Method overriding is a feature of object-oriented programming in which a subclass provides its own implementation of a method that is already defined in its parent class. When a method in a subclass has the same name, parameters, and return type as a method in its parent class, it is said to override the parent class method.
The main purpose of method overriding is to provide a specific implementation of a method in a subclass that is different from the implementation in the parent class. This allows the subclass to have its own behavior for the method, which is useful when the subclass needs to perform a specific task that is not already defined in the parent class.
To override a method in a subclass, the method must have the same name, parameters, and return type as the method in the parent class. The access level of the method in the subclass cannot be more restrictive than the access level of the method in the parent class. If the method in the parent class is declared as final or private, it cannot be overridden in the subclass.
Here's a program in java that demonstrate the use of Method Overriding
class Shape { public void draw() { System.out.println("Drawing shape"); }}
class Rectangle extends Shape { public void draw() { System.out.println("Drawing rectangle"); }}
class Circle extends Shape { public void draw() { System.out.println("Drawing circle"); }}
public class MethodOverridingDemo { public static void main(String[] args) { Shape shape1 = new Shape(); shape1.draw(); // Drawing shape
Rectangle rect = new Rectangle(); rect.draw(); // Drawing rectangle
Circle circle = new Circle(); circle.draw(); // Drawing circle }}
Drawing shape
Drawing rectangle
Drawing circle
In this program, we have a shape class with a draw() method that prints "Drawing shape" to the console. The rectangle and circle classes are subclasses of shape, and they both override the draw() method to print their own shapes.
When we run the program, it creates instances of the shape, rectangle, and circle classes and calls their draw() methods.
As we can see, the rectangle and circle classes override the draw() method from the shape class to provide their own implementation. This is an example of method overriding in java, where a subclass provides its own implementation of a method that is already defined in its parent class.