abstract-interface

Abstrakte Klassen


Motivation

uml chess

public class ChessPiece {
    public void move() {
        // ?
    }
}
  • chessPiece.play()?
  • new ChessPiece()?

abstract

public abstract class ChessPiece {
    private Position position;

    protected ChessPiece(Position position) {
        this.position = position;
    }

    public abstract void move();
}
  • abstract Methode hat keinen Body
  • abstract Methode ⟹ Klasse abstract
  • new AbstractClass() 🚫
  • Konstruktor für super() ✔️

  • Childklassen müssen alle abstract Methoden überschreiben
  • 
    public class King extends ChessPiece {
        @Override
        public void move() {
            moveKnightly();
        }
    }
    
  • oder selbst abstract sein
  • 
    public abstract class RoyalChessPiece extends ChessPiece {}
    

Sicher nicht

private abstract
man kann nicht overriden
final abstract
man darf nicht overriden
static abstract
statische Member werden nicht vererbt
native abstract
native - Code liegt kompiliert vor

interface

public interface Flyable {
    double GRAVITY = 9.80665;
    void fly();
}
  • definiert Verhalten
  • Fields implizit public static final
  • Methoden implizit public abstract
  • keine Konstruktoren
  • als Compiletyp zulässig
  • Klassen implementieren das Interface
  • kann mehrere andere Interfaces extenden
  • Implementierung checken mit instanceof

class Eagle extends Bird implements Flyable, Serializable {
    @Override
    void fly() {
        flyHigh(GRAVITY);
    }
abstract class FlyingBird extends Bird implements Flyable {}
Flyable[] airForce = new Flyable[50];
airForce[0] = new Jet();
airForce[1] = new Airship();
airForce[2] = new Balloon();
...

for (Flyable flyer : airForce)
    flyer.fly();
interface Crashable extends Flyable, Speedable {
    void crash();
}

default/static


public interface Speedable {
    double KM_PER_MPH = 1.60934;
    void speed();

    default void callForHelp() {
        PhoneService.call("122");
    }

    static double convertMphToKmh(double mph) {
        assertValidMph(mph);
        return mph * KM_PER_MPH;
    }

    private static void assertValidMph(double mph) {
        if (!Double.isFinite(mph)) 
            throw new IllegalArgumentException("Invalid speed: " + mph);
    }
}

Klassen können default-Methoden overriden