wisconsin
Polymorphism

Polymorphism

Curated by Last modified: 2 min read

Polymorphism is the ability of an object to take on many forms. The most common use of polymorphism in OOP occurs when a parent class reference is used to refer to a child class object.

Polymorphism in Java

A common example of polymorphism in Java is when a parent class reference is used to refer to a child class object. For example, consider the following classes:

class Animal {
    public void makeSound() {
        System.out.println("Animal makes a sound");
    }
}

class Dog extends
Animal {
    @Override
    public void makeSound() {
        System.out.println("Dog barks");
    }
}

In this example, the Dog class extends the Animal class and overrides the makeSound() method. You can create an object of the Dog class and assign it to a reference of the Animal class:

Animal myDog = new Dog();
myDog.makeSound(); // Output: Dog barks

In this case, the makeSound() method of the Dog class is called, even though the reference is of type Animal. This is an example of polymorphism in Java.

Tip

The logic behind method selection is known as dynamic method selection (DMS). The method to be executed is determined at runtime based on the actual type of the object, not the reference type.

While CS300 does not talk about DMS explicitly, UC Berkeley’s CS61B course does. You can read more about DMS here

Interfaces

Interfaces are a way to achieve polymorphism in Java. An interface is a reference type in Java that is similar to a class but can only contain method signatures and constants. An interface cannot contain method implementations.

To define an interface in Java, you use the interface keyword followed by the interface name:

interface Animal {
    void makeSound();
}

A class can implement an interface by using the implements keyword:

class Dog implements Animal {
    @Override
    public void makeSound() {
        System.out.println("Dog barks");
    }
}

Interfaces are more flexible than classes because a class can implement multiple interfaces. This allows you to achieve polymorphism in Java by defining multiple interfaces and having classes implement them.

However, interfaces can only contain method signatures and constants, not method implementations. This means that any class that implements an interface must provide an implementation for all the methods defined in the interface.

Source

The existing course note was retained and normalized during the merge.

Related: Topic index.

Linked to this page