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

Static Methods

  • Static methods belong to all instances of an object
  • If a method can exist without an instance of an object, use a static method
Simple examples

The variable PI is the same for all instances of an object.

public class Circle {
  public static final double PI = 3.141592653589793;
}

The Math class methods do not change between instances

Math.abs()
Math.sqrt()
etc

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 implements 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?

Abstract Classes

  • Similar to interfaces
  • Can contain concrete methods
  • Can not be instantiated
  • Can be subclassed
  • If a class contains abstract methods, then the class must be marked as abstract
  • Sub-classes must provide concrete methods for abstract methods or be abstract itself
  • Used when subclasses have a lot in common (implemented) and saves some of the details to be implemented later (abstract)
Example, drawing shapes

Example adapted from http://docs.oracle.com/javase/tutorial/java/IandI/abstract.html

Graphic objects in Java may share many similar methods, such as moving a graphic to a new x,y coordinate, the current position, the current fill color, etc. However, other methods need to be implemented specifically for certain shapes. This is a great place to use an abstract class.

abstract class GraphicObject {
    int x, y;
    ...

    protected void moveTo(int newX, int newY) {
        ...
    }

    protected Color getFillColor() {
        ...
    }

    ...

    protected abstract void draw();
    protected abstract void resize();
}

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.
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);
  }
}
Square square = new Square(5);
System.out.println(square.getArea());

Method Overloading

  • Method overloading is a form of polymorphism which allows multiple methods with the same name to exist as long as their parameters are different
  • Constructors can also be overloaded
Overloading Example
public static Loan createLoan(Lender lender) {
  // Use default interest rate
}

public static Loan createLoan(Lender, double interestRate) {
  // Use provided interestRate
}

Method Overriding

  • Override a method replaces a method in the parent class with the same signature
  • The @Override annotation should be used
  • toString is a common example

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 animal = 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();
In lab discussion

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

Clone this wiki locally