Created: 2023-08-25 20:45
Status: #concept
Subject: Programming
Tags: Java Object-Oriented Programming Inheritance SOLID Principles

Polymorphism

It is the concept of allowing children of a parent Class to redefine or override Properties and Methods Inherited from the parent.

  • this allows us to inherit from the same parent, but let a subclass get assigned to references where the parent can, but act differently due to the redefinition of its Methods.

public static void main(String[] args) {
  Employee joe = new Employee("Average Joe");
  Employee chad = new Manager("Chad");

  joe.introduce(); // Hello, I am Average Joe, an employee!
  chad.introduce(); // Hello, I am Chad, and I manage a Local Branch.
}

public static class Employee {
  String name;
  int id;
  String department = "General";
  
  Employee(String n) {
    name = n;
  }

  void introduce() {
    System.out.println("Hello, I am " + name + ", an employee!");
  }
}

public static class Manager extends Exployee {
  String department = "Local Branch";

  Manager(String n) {
    super(n);
  }

  @Override
  void introduce() {
    System.out.println("Hello, I am " + name + ", and I manage a ", + department);
  }

}

References