Java Interfaces

  • Use the interface keyword
  • Usually only methods
  • All methods public abstract
  • All attributes public static final
  • No constructor, no code

Java Interface Example

public interface IMyQueue {
    void enqueue(Object o);
    Object dequeue();
    Object peek();
    int size();
}

Using a Java Interface

public class WaitingList implements IMyQueue {
    public void enqueue(Object o) {
        //code here
    }
public Object dequeue() { //code here }
public Object peek() { //code here }
public int size() { //code here } }

Interfaces are Types

IMyQueue wait = new WaitingList();
wait.enqueue(new Person());
wait.dequeue();

We can call any methods
defined by the interface

Java Inheritance

  • Subclass inherits all state and behavior
  • Subclass has all public and protected attributes and methods of superclass
  • Subclass constructor can call super() constructor
  • Subclass can override superclass methods with new code
public class Canine {
    protected name;
    public void bark() {
        //code here
    }
}
public class Dog extends Canine { protected owner; public void pet() { //code here } }
public class GuideDog extends Dog { protected trainer; public void guide() { //code here } }
Subclass has all Superclass behaviors
GuideDog lassie = new GuideDog();
lassie.bark();
lassie.pet();
lassie.guide();

Multiple Inheritance

Classes in Java can only
directly inherit from one superclass

Classes may implement
any number of interfaces