Skip to content
Anthony Christe edited this page Sep 11, 2013 · 3 revisions

Interfaces

  • Creates a protocol (contract) that any class implementing a certain interface has certain features
  • Example - [Comparable] (http://docs.oracle.com/javase/7/docs/api/java/lang/Comparable.html)
  • An interface file simple lists the public method signatures that need to be implemented by all classes implementing the interface
  • A class implementing an interface uses the syntax public ClassName implements InterfaceNameOne, InterfaceNameTwo, ... {...
  • An interface can also contain final and static fields
  • All methods declared in an interface must be implemented in implementing classes
  • Interfaces can be extended

An example interface of a vehicle

public interface Vehicle {
  public void startEngine();
  public void changeGear(int gear);
  public int accelerate(int amount);
  public void brake(int amount);
  public void getSpeed();
  public void turn(int amountLeft, int amountRight, int amountUp, int amountDown);
}

Implementing the interfaces

public class Motorcycle implements Vehicle {
  /**
   * Starts the engine
   */
  public void startEngine() {
    changeGear(0);
    // apply clutch
    // kick start
  }
  
  /**
   * Changes to specified gear
   *
   * @param gear The gear to shift into
   */
  public void changeGear(int gear) {
    // apply clutch
    // let off gas
    // use gear shift foot pedal
  }
  
  /**
   * Accelerates the vehicle by a certain amount
   *
   * @param amount The amount to accelerate by
   * @return  The speed the vehicle will be moving after accelerating
   */
  public int accelerate(int amount) {
    // Turn acceleration grip on handlebar 
  }
  
  /**
   * Applies the break by a certain amount
   *
   * @param amount the amount to apply the brake where amount is some percentage between 0-100%
   */
  public void brake(int amount) {
    // squeeze right break
  }
  
  /**
   * Returns the current speed of the vehicle
   */
  public int getSpeed() {
    // return number of rotations * diameter of tire in miles per hour
  }
  
  /*
   * Turns the vehicle in the specified directions using the specified amounts
   *
   * @param amountLeft  The amount in degrees to turn to the left
   * @param amountRight The amount in degrees to turn to the right
   * @param amountUp    The amount in degrees to turn to the up
   * @param amountDown  The amount in degrees to turn to the down
   */
  public void turn(int amountLeft, int amountRight, int amountUp, int amountDown) {
    // turn handle bars so many degrees to go the direction we want to go
    // ignore up and down amounts
  }
}
public class FighterJet extends Vehicle {
  public void startEngine() {
    // Increase fuel flow
    // Balance air flow
    // Ignite engines
  }
  
  public void changeGear(int gear) {
    // Do nothing
  }
  
  public int accelerate(int amount) {
    // Increase throttle stick
    // Max speed would be significantly different for a fighter jet compared to a motorcycle
  }
  
  public void brake(int amount) {
    // Decrease throttle stick
    // Increase flaps
  }
  
  public int getSpeed() {
    // Do calculations for airspeed
  }
  
  public void turn(int amountLeft, int amountRight, int amountUp, int amountDown) {
    // Change position of elevators
    // Change position of rudders
    // Change position of flaps
  }
}

We might also consider extending our Vehicle interface with a FlyingVehicle interface...

public interface FlyingVehicle extends Vehicle {
  public void land();
  public void takeOff();
}
Lab work

Create a CardGame interface. What public methods would you expect to see in a card game?

Inheritance

  • Powerful tool enabling code reuse
  • Create a base class, then extend it to add additional functionality
  • When a class extends another class, the class it extends is said to be the parent class
  • Subclasses gain access to all public and protected members of parent class
What can we do in a subclass?

Notes adapted from http://docs.oracle.com/javase/tutorial/java/IandI/subclasses.html

  • The inherited fields can be used directly, just like any other fields.
  • You can declare a field in the subclass with the same name as the one in the superclass, thus hiding it (not recommended).
  • You can declare new fields in the subclass that are not in the superclass.
  • The inherited methods can be used directly as they are.
  • You can write a new instance method in the subclass that has the same signature as the one in the superclass, thus overriding it.
  • You can write a new static method in the subclass that has the same signature as the one in the superclass, thus hiding it.
  • You can declare new methods in the subclass that are not in the superclass.
  • You can write a subclass constructor that invokes the constructor of the superclass, either implicitly or by using the keyword super.
In lab discussion

How would you model the community of people at a university? How would you use inheritance and interfaces?

Example
public class Rectangle {
  protected int width, height;
  
  public Rectangle(int width, int height) {
    this.width  = width;
    this.height = height;
  }
  
  protected int getArea() {
    return this.width * this.height;
  }
  
  protected int getPerimeter() {
    return (this.width * 2) + (this.height * 2);
  }
}
public class Square extends Rectangle {
  public Square(int length) {
    super(length, length);
  }
}

Polymorphism

  • Method overloading and method overriding are types of polymorphism (ad-hoc)
  • The use of generics is a form of polymorphism (parametric)
  • Dynamic (or late method) binding is a form of polymorphism
  • Polymorphism allows an object to take several forms
Examples

Examples adapted from [Examples adapted from http://www.tutorialspoint.com/java/java_polymorphism.htm](Examples adapted from http://www.tutorialspoint.com/java/java_polymorphism.htm)

public interface Vegetarian{}
public class Animal{}
public class Deer extends Animal implements Vegetarian{}

Deer deer = new Deer();
Animal aanimal = deer;
Vegetarian vegetarian = deer;
Object object = deer;

And another example adapted from http://home.cogeco.ca/~ve3ll/jatutor5.htm using dynamic method binding.

public class Animal {
  protected String name;
  
  public Animal(String name) {
    this.name = name;
  }
}
public interface Talking {
  protected void speak();
}
public class Cow extends Animal implements Talking {
  public Cow(String name) {
    super(name);
  }
  
  protected void speak() {
    System.out.println("Moo, my name is " + this.name);
  }
}
public class Dog extends Animal implements Talking {
  public Dog(String name) {
    super(name);
  }
  
  protected void speak() {
    System.out.println("Bark, my name is " + this.name);
  }
}
public class Snake extends Animal implements Talking {
  public Snake(String name) {
    super(name);
  }
  
  protected void speak() {
    System.out.println("(unintelligible Parseltongue)");
  }
}
Animal animal;
Cow cow   = new Cow("Bossy"); // makes specific objects
Dog dog   = new Dog("Rover");
Snake snake = new Snake("Ernie");
  
animal = cow;
animal.speak();
  
animal = dog;
animal.speak();
  
animal = snake;
animal.speak();

Clone this wiki locally