Welcome back to CodeYourCraft! Today, we're diving into an exciting concept called Java Method Overriding. This feature is a powerful tool that allows us to customize the behavior of methods in a child class that already exists in the parent class. Let's get started!
Method Overriding is a process in Java where a subclass provides its own implementation for a method that already exists in its parent class. The idea is to override the parent class's method with a new implementation in the child class.
Method Overriding is crucial for maintaining polymorphism, a fundamental feature of object-oriented programming. It allows us to treat different objects of different classes as if they were objects of a common superclass.
Let's create a simple example to understand Method Overriding better.
// Parent Class
public class Animal {
public void makeSound() {
System.out.println("The animal makes a sound.");
}
}
// Child Class
public class Dog extends Animal {
@Override
public void makeSound() {
System.out.println("Woof Woof!");
}
}In the example above, we have a Animal parent class with a makeSound() method. The Dog class extends the Animal class and overrides the makeSound() method to provide a specific barking sound for dogs.
In certain cases, a parent class method and the corresponding child class method may have the same name but different return types. This is known as Method Overloading. However, in Java, we can't achieve this through method overloading. Instead, we can use Method Overriding with an upcasting technique.
// Parent Class
public class Shape {
public double getArea() {
System.out.println("Cannot calculate area for general Shape.");
return 0;
}
}
// Child Class
public class Square extends Shape {
private final double side;
public Square(double side) {
this.side = side;
}
@Override
public double getArea() {
return side * side;
}
}
// Main Class
public class Main {
public static void main(String[] args) {
Square square = new Square(5);
Shape shape = square; // Upcasting
System.out.println(shape.getArea()); // Output: 25
}
}In the above example, we have a Shape parent class with a getArea() method that doesn't calculate the area for a general shape. The Square class extends the Shape class and overrides the getArea() method to calculate the area for squares. In the main method, we create a Square object and upcast it to a Shape object, demonstrating how the overridden method is invoked.
What is Method Overriding in Java?
That's all for today's lesson on Java Method Overriding! We hope you found this tutorial helpful. Don't forget to practice and experiment with these concepts in your own projects. Happy coding! 💻🥳