Java Three programs to method overriding. Three Java programs demonstrating method overriding, along with step-by-step explanations and outputs.
Program-1: Basic Method Overriding
java class Animal { void sound() { System.out.println("Animal makes a sound"); } } class Dog extends Animal { void sound() { System.out.println("Dog barks"); } } public class Main { public static void main(String[] args) { Animal myDog = new Dog(); myDog.sound(); } }
Explanation:
1. Class Hierarchy: We have a base class `Animal` with a method `sound()`. The `Dog` class extends `Animal` and overrides the `sound()` method.
2. Object Creation: In the `main` method, we create a reference of type `Animal` but instantiate it with `Dog`.
3. Method Call: When `myDog.sound()` is called, it invokes the overridden `sound()` method in the `Dog` class.
Output:
Dog barks
Program-2: Method Overriding with Parameters
java class Vehicle { void display(int speed) { System.out.println("Vehicle speed: " + speed + " km/h"); } } class Car extends Vehicle { void display(int speed) { System.out.println("Car speed: " + speed + " km/h"); } } public class Main { public static void main(String[] args) { Vehicle myCar = new Car(); myCar.display(120); } }
Explanation:
1. Class Hierarchy: `Vehicle` has a method `display(int speed)`. The `Car` class overrides this method.
2. Object Creation: We create a `Vehicle` reference to a `Car` object.
3. Method Call: The `display(int speed)` method of `Car` is invoked.
Output:
Car speed: 120 km/h
Program-3: Method Overriding with Return Types.
java class Shape { String draw() { return "Drawing a shape"; } } class Circle extends Shape { @Override String draw() { return "Drawing a circle"; } } public class Main { public static void main(String[] args) { Shape myShape = new Circle(); System.out.println(myShape.draw()); } }
Explanation:
1. Class Hierarchy: `Shape` has a method `draw()` that returns a `String`. The `Circle` class overrides this method.
2. Object Creation: A `Shape` reference points to a `Circle` object.
3. Method Call: When `myShape.draw()` is called, it invokes the overridden method in `Circle`.
Output:
Drawing a circle
Summary
1. Basic Overriding: Shows simple method overriding with no parameters.
2. Overriding with Parameters: Demonstrates method overriding with parameters, showing that the method signature (name and parameter type) must match.
3. Overriding with Return Types: Highlights that the return type can be the same or a subtype, enabling polymorphism.
In all cases, the method of the subclass is invoked based on the object type, showcasing the core principle of method overriding in Java.(Java Three programs to method overriding.)