Polymorphism

Description:

Polymorphism: subclasses of a class can be defined by their own unique behaviors and yet share some of the same functionality of the parent class. 

Packages: a namespace for organizing classes and interfaces in a logical manner.

When to usePolymorphism is a programming concept that refers to a class that constantly changes its states or functionality through the extension/ Inheritance of subclasses.

Exmaple:

Class:

package ploymorphism;

public class Employee {

    private String name;
  
 private int id;
    
    
public Employee(String name, int id){
        
this.name = name;
        
this.id = id;
    }
    
    
public void print(){
        System.
out.println("Employee Name: " + name + ","+ " Employee ID: " + id);
    }
}

SubClass:

package ploymorphism;

public class FullTime extends Employee {
    
    
private double salary;
    
    FullTime(String
name, int id, double salary){
        
super(name, id);
        
this.salary = salary;
    }
    

    public void print(){
        
super.print();
        System.
out.println("Employee's salary is "+ salary);
    }
}

SubClass:

package ploymorphism;

public class PartTime extends Employee {
    
    
private double rate;
    
    PartTime(String
name , int id, double rate){
        
super(name, id);
        
this.rate = rate;
    }
    
  
 public void print(){
        
super.print();
        System.
out.println("Employee's rate is "+ rate);
    }
}

Main class:

package ploymorphism;

public class Main {
  
 public static void main(String [] args){
        
        Employee
employees[] = new Employee[3];
        
employees[0] = new FullTime("Jessie", 12345, 52030.20);
        
employees[1] = new FullTime("James", 12346, 60750.02);
        
employees[2] = new PartTime("Meowth", 12344, 23.75);
        
        
for(Employee employee : employees){
            
employee.print();
        }
    }
}

 

Results:

Employee Name: Jessie, Employee ID: 12345
Employee's salary is 52030.2
Employee Name: James, Employee ID: 12346
Employee's salary is 60750.02
Employee Name: Meowth, Employee ID: 12344
Employee's rate is 23.75

Challenge Problem

Leave a Reply