Object Oriented

Polymorphism

Java

 

Polymorphism

Java 8
// InfoInterface.java file
interface InfoInterface {
  public String getInfo();
}

// Teacher.java file
class Teacher implements InfoInterface {
  public String name;
  public int salary;
  
  public Teacher(String name, int salary) {
    this.name = name;
    this.salary = salary;
  }
  
  public String getInfo() {
    return "name: " + name +
         ", salary: " + salary;
  }
}

// Student.java file
class Student implements InfoInterface {
  public String name;
  public double gpa;
  
  public Student(String name, double gpa) {
    this.name = name;
    this.gpa = gpa;
  }
  
  public String getInfo() {
    return "name: " + name +
         ", gpa: " + gpa; 
  }
}

Polymorphism provides a way for classes with different functionality to share a common interface.

Polymorphism lets you to have different objects from different classes, but with all of them guaranty to have at least a method with a same signature that can be called without knowing the type of the object.

InfoInterface[] people = new InfoInterface[4];

people[0] = new Student("Bob", 3.5);
people[1] = new Teacher("Alice", 80000);
people[2] = new Student("Emma", 4);
people[3] = new Student("Liam", 2.8);

for (int i=0; i<people.length; i++) {
    InfoInterface person = people[i];
    System.out.println(person.getInfo());
}

The output for the code above will be:

name: Bob, gpa: 3.5
name: Alice, salary: 80000
name: Emma, gpa: 4.0
name: Liam, gpa: 2.8