course content

Course Content

Introduction to Java

Polymorphism and Method OverridingPolymorphism and Method Overriding

Polymorphism is a fancy word that means "many shapes" or "many forms". In Java, polymorphism is all about ensuring that objects can be treated as objects of their parent class or objects of any of their subclasses. There are two types of polymorphism in Java:

  • Method Overloading Polymorphism: When a class has multiple methods with the same name but different parameters, it's called method overloading polymorphism;
  • Method Overriding Polymorphism: When a subclass provides a new implementation of a method already defined in its superclass, it's called method overriding polymorphism. These types of polymorphism allow us to write more flexible and reusable code. In this lesson, we'll focus on method overriding polymorphism.

What is Method Overriding?

Method Overriding is when you have a subclass that provides its implementation of a method that is already defined in its parent class. This way, the subclass can have its version of the method different from the one in the parent class. Let's take an example of vehicles to understand polymorphism and method overriding. Imagine that you have a parent class called Vehicle and two subclasses, Car and Bike. The Vehicle class has a method called move, and both the Car and Bike classes have their version of the move method. When you create objects of Car and Bike, you can call the move method on those objects, and the correct version of the move method will be called based on which object you are calling the method on. This is polymorphism! Let's look at the code to understand it better:

java

Main.java

As you can see, when you call the move method on a Vehicle object, it prints a "Vehicle is moving". But when you call the move method on a Car object, it prints Car is moving, and when you call the move method on a Bike object, it prints Bike is moving. This is polymorphism and method overriding in action! So, polymorphism and method overriding are very important parts of Java programming. It helps you create objects that can be treated as objects of their parent class or objects of any of their subclasses. So, you've learned about polymorphism and method overriding. Well done!

1. What is method overriding?
2. What is the purpose of method overriding in polymorphism?

question-icon

What is method overriding?

Select the correct answer

question-icon

What is the purpose of method overriding in polymorphism?

Select the correct answer

Section 3.

Chapter 5