OOPS

Problem: There are employees of two kinds A & B. A is a government employee and B is a private employee. A gets a basic salary & DA, whereas B gets a basic salary & gets a fixed commision for the given amount of sales. Write a program to show the name & total salary of employee of each kind. Let, Kritika is category A employee & Sumit is a category B employee.

Programming Language & Compilation

$ javac Program.java
$ java Program

Source Code

import java.lang.System;

// * Provides a label.
// * Responsible for runtime-polymorphism.
// * Identifies the type of the object using superclass.
// * "discriminator part".
interface SalaryCalculator {
  public double calculateSalary();
}

class CategoryA implements SalaryCalculator {
  double basicSalary, da;

  // Parameterized constructor.
  CategoryA(double basicSalary, double da) {
    this.basicSalary = basicSalary;
    this.da = da;
  }

  // Implement the calculateSalary from SalaryCalculator interface.
  public double calculateSalary() {
    return (basicSalary + da);
  }
}

class CategoryB implements SalaryCalculator {
  double basicSalary;
  int salesQuanitity;
  static final double commission = 0.5;

  // Parameterized constructor.
  CategoryB(double basicSalary, int salesQuanitity) {
    this.basicSalary = basicSalary;
    this.salesQuanitity = salesQuanitity;
  }

  // Implement the calculateSalary from SalaryCalculator interface.
  public double calculateSalary() {
    return (basicSalary + (salesQuanitity * commission));
  }
}

class Employee {
  String name;
  SalaryCalculator salaryCalculator;

  // Take the employee's name as String & the reference to instance of
  // SalaryCalculator to store the employee's type.
  Employee(String name, SalaryCalculator salaryCalculator) {
    this.name = name;
    this.salaryCalculator = salaryCalculator;
  }

  // Display method to display the employee's name and salary.
  void display() {
    System.out.println("Name: " + name);
    System.out.println("Salary: " + salaryCalculator.calculateSalary());
  }
}

public class Program {
  public static void main(String[] args) {
    CategoryA categoryA = new CategoryA(10000, 4000);
    CategoryB categoryB = new CategoryB(4000, 200);
    Employee employee1 = new Employee("Kritika", categoryA);
    employee1.display();
    Employee employee2 = new Employee("Sumit", categoryB);
    employee2.display();
  }
}

Output

right-click & select “Open image in new tab” for larger image.

Notes

interface abstract
1. No modification in classes in future. 1. Modification is allowed.
2. Used like a marker. 2. Used as a marker.
3. Used with otherwise un-related classes. 3. Only used with related classes.
4. No extensiblity. 4. Extensiblity.

UML Diagram