Java Polymorphism

What is Polymorphism?

Polymorphism means "many forms." It allows the same method name to perform different actions depending on the object.

This is a key concept in OOP that works closely with inheritance.

Loading...
Output:

Method Overriding

Method overriding allows a subclass to provide its own implementation of a method defined in the parent class.

The method name and parameters must be the same, but the behavior can change.

Loading...
Output:

Using Parent References

You can use a parent class reference to point to a child object. This is where polymorphism becomes powerful.

The method that runs depends on the actual object type, not the reference type.

Loading...
Output:

Method Overloading

Method overloading allows multiple methods with the same name but different parameters.

Java decides which method to use based on the arguments passed.

Loading...
Output:

Runtime vs Compile-Time

Overriding is resolved at runtime based on the object type. Overloading is resolved at compile time based on method signatures.

Loading...
Output:

Why Use Polymorphism?

Polymorphism allows you to write flexible and reusable code by working with general types instead of specific ones.

  • Reduces code duplication
  • Improves scalability
  • Works well with inheritance

Practice

Create Shape, Circle, and Rectangle classes with overridden draw() methods.

Loading...
Output:

Need Help?