# Polymorphism

Source: https://wisconsin.twango.dev/fa24-cs300/u2-oop/inheritance/polymorphism

# Polymorphism

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:

```java
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:

```java
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][CS61B] course does. You can read more about DMS [[u2-oop/inheritance/dynamic-method-selection|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:

```java
interface Animal {
    void makeSound();
}
```

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

```java
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.

[CS61B]: https://datastructur.es/

## Source

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

Related: [[u2-oop/inheritance/index|Topic index]].
