物件導向 Object-Oriented

可說是將現實世界虛擬化
或以程式語言來描繪現實世界

屬性(field)代表物體的各種狀態(state)
方法(method)代表物體的各種行為(behavior)

例如:
狗有四條腿,會汪汪叫
鳥有翅膀,會飛
魚有鰭,會游泳

我們可以訂出以下藍圖(blueprint)或模型(model)

class Dog {
    Double height;
    Double weight;
    public void eat() {}
    public void walk() {}
}

class Cat {
    Double height;
    Double weight;
    public void eat() {}
    public void walk() {}
}

class Bird {
    Double height;
    Double weight;
    public void eat() {}
    public void fly() {}
}

class Fish {
    Double height;
    Double weight;
    public void eat() {}
    public void swim() {}
}

這樣就能藉由類別(class)產生實例(instance)

Dog yellow = new Dog();
Dog black = new Dog();
Dog white = new Dog();

同一 class 的實例當然具有相似的特徵
小黑、小黃、小白雖然顏色不一樣,但牠們都是狗

一旦物件多了會發現滿多物件有共通點
可以藉由繼承(inherit)來去除重複性
例如:狗、鳥、魚都是動物,都有身高體重,都會吃

class Animal {
    Double height;
    Double weight;
    public void eat() {}
}

class Dog extends Animal {
    public void walk() {}
}

class Cat extends Animal {
    public void walk() {}
}

class Bird extends Animal {
    public void fly() {}
}

class Fish extends Animal {
    public void swim() {}
}

Animal 是 Dog 的 superclass
Dog、Bird、Fish 是 Animal 的 subclasses
subclass 會繼承 superclass 的屬性與方法

方法也能抽出變為介面(interface)

interface Eatable {
    void eat();
}

interface Walkable {
    void walk();
}

interface Flyable {
    void fly();
}

interface Swimmable {
    void swim();
}

class Animal implements Eatable {
    Double height;
    Double weight;
    public void eat() {}
}

class Dog extends Animal implements Walkable {
    public void walk() {}
}

class Cat extends Animal implements Walkable {
    public void walk() {}
}

class Bird extends Animal implements Flyable {
    public void fly() {}
}

class Fish extends Animal implements Swimmable {
    public void swim() {}
}