Slide 1
Slide 2
Slide 3

Polymorphism in java programming (V50)

No Comments

Polymorphism

The word “polymorphism” means “many forms.” In object-oriented programming, polymorphism is useful when you want to create multiple forms with the same name of a single entity. To implement polymorphism in Java, we use two concepts: method overloading and method overriding.

  • Method overloading is implemented within the same class, where we have multiple methods with the same name but different parameters.

  • Method overriding is implemented using inheritance, where we can have multiple methods with the same name in the parent class and the child class.

    Source Code: Polymorphism.java

Copied!
// Superclass
class Person {
    void displayInfo() {
        System.out.println("This is a person.");
    }
}

// Subclass
class Student extends Person {
    // Overriding method
    @Override
    void displayInfo() {
        System.out.println("This is a student.");
    }
}

// Another Subclass
class Teacher extends Person {
    @Override
    void displayInfo() {
        System.out.println("This is a teacher.");
    }
}

// Main class
public class Polymorphism {
    public static void main(String[] args) {
        // Polymorphism: same reference, different object types
        Person p1 = new Person();
        Person p2 = new Student();  // upcasting
        Person p3 = new Teacher();  // upcasting

        // Call the same method on all objects
        p1.displayInfo();  // Calls Person version
        p2.displayInfo();  // Calls Student version
        p3.displayInfo();  // Calls Teacher version
    }
}

Result:


Watch the video:

back to top