Curriculum
Course: Java Basic
Login

Curriculum

Java Basic

Java Home

0/1

Java Introduction

0/1

Java Get Started

0/1

Java Syntax

0/1

Java Comments

0/1

Java Type Casting

0/1

Java Operators

0/1

Java Booleans

0/1

Java Switch

0/1

Java Break / Continue

0/1

Java Errors and Exception

0/1
Text lesson

Java Polymorphism

Java Polymorphism

Polymorphism, derived from “many forms,” arises when multiple classes are interconnected through inheritance.

As mentioned in the preceding chapter, Inheritance facilitates the acquisition of attributes and methods from another class. Polymorphism leverages these methods to execute diverse tasks, enabling the execution of a singular action through various approaches.

Consider a superclass named Animal containing a method called animalSound(). Subclasses of Animal, such as Pigs, Cats, Dogs, and Birds, possess their unique implementations of animal sounds (for instance, pigs oink and cats meow).

Example

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

 class Pig extends Animal {
  public void animalSound() {

   System.out.println("The pig says: wee wee");
  }
} class Dog extends Animal { public void animalSound() {   System.out.println("The dog says: bow wow"); } }

 

Recall from the Inheritance chapter that we use the extends keyword to inherit from a class.

Now, we have the capability to instantiate Pig and Dog objects and invoke the animalSound() method on each of them:

Example

class Animal {

  public void animalSound() {

    System.out.println(“The animal makes a sound”);

  }

}

 class Pig extends Animal {

  public void animalSound() {

    System.out.println(“The pig says: wee wee”);

  }

}

 

class Dog extends Animal {

  public void animalSound() {

    System.out.println(“The dog says: bow wow”);

  }

}

 class Main {

  public static void main(String[] args) {

    Animal myAnimal = new Animal();  // Create a Animal object

    Animal myPig = new Pig();  // Create a Pig object

    Animal myDog = new Dog();  // Create a Dog object

    myAnimal.animalSound();

    myPig.animalSound();

    myDog.animalSound();

  }

}

 

Why And When To Use “Inheritance” and “Polymorphism”?

It facilitates code reusability by allowing you to utilize the attributes and methods of an existing class when defining a new class.