Tuesday, March 29, 2011

Interfaces

Here's a UML diagram of this week's tutorial discussion:


public void test()
{
    System.out.println("Enter ID");
    int id = scanner.nextInt();
    Employee employee = findEmployeeById(id);
    displaySalary(employee);
}

public void displaySalary(Programmer programmer)
{
    System.out.println(programmer.calculateSalary());
}

public void displaySalary(TeamLeader teamLeader)
{
    System.out.println(teamLeader.calculateSalary());
}


I need  to change the test method as follows:

public void test()
{
    System.out.println("Enter ID");
    int id = scanner.nextInt();
    Employee employee = findEmployeeById(id);
    displaySalary(employee);
    if (employee instanceof Programmer)
      System.out.println ((Programmer)employee.calculateSalary());
    elseif (employee instanceof TeamLeader)
      System.out.println ((TeamLeader)employee.calculateSalary());
    elseif (employee instanceof Cleaner)
      System.out.println ((Cleaner)employee.calculateSalary());
}


This isn't very good, because it's not very scalable. Every time a new class is created, it will need to be extended.

This is when interface comes in handy. Very little goes in the interface, the implementation is specified in the classes that implement it.

public interface SalariedWorker
{
    double calculateSalary;
}

public class TeamLeader implements SalariedWorker
{
    public double calculateSalary()
    {
        return 100 * 100
    }
}

public class Programmer implements SalariedWorker
{
    public double calculateSalary()
    {
        return 50 * 50
    }
}


Now I need to change my test method to implement the interface

public void test()
{
    System.out.println("Enter ID");
    int id = scanner.nextInt();
    Employee employee = findEmployeeById(id);
    displaySalary(employee);
    if (employee instanceof SalariedWorker)
      displaySalary((SalariedWorker)employee);
    else System.out.println("The employee is not a salaried worker");
}


And that's how to use interfaces.

My thoughts:
This makes sense to me, it's a much nicer way to determine if the subclass has a method. I haven't used instanceof before, I was wondering how you check what type of subclass something is.

2 comments:

  1. Do you have to do the cast to SalariedWorker or will it still work without?

    ReplyDelete
  2. You need to cast to SalariedWorker because you created employee as an instance of Employee, which doesn't have the displaySalary method

    ReplyDelete