Java インターフェース

概要

動物の振る舞いを表すインターフェースを実装した犬と猫のクラスを作り、それらのオブジェクトの動きを確認する。

import java.io.IOException;

interface Animal {
    public abstract void eat(String food);

    public abstract void sing();
}

class Dog implements Animal {
    Dog() {
        System.out.println("Dogクラスのオブジェクトを生成しました。");
    }

    public void eat(String food) {
        if (food == "ドッグフード") {
            System.out.println(food + "を食べる。");
        } else {
            System.out.println(food + "食べない。");
        }
    }

    public void sing() {
        System.out.println("ワン!");
    }
}

class Cat implements Animal {
    Cat() {
        System.out.println("Catクラスのオブジェクトを生成しました。");
    }

    public void eat(String food) {
        if (food == "キャットフード") {
            System.out.println(food + "を食べる。");
        } else {
            System.out.println(food + "食べない。");
        }
    }

    public void sing() {
        System.out.println("ニャー!");
    }

}

public class AnimalInterfaceTest {
    public static void main(String[] args) throws IOException {
        Dog inu = new Dog();
        Cat neko = new Cat();

        inu.eat("ドッグフード");
        inu.eat("草");
        inu.sing();

        neko.eat("キャットフード");
        neko.eat("ドッグフード");
        neko.sing();
    }

}

実行結果

Dogクラスのオブジェクトを生成しました。
Catクラスのオブジェクトを生成しました。
ドッグフードを食べる。
草食べない。
ワン!
キャットフードを食べる。
ドッグフード食べない。
ニャー!

Interface(インターフェース)2015年10月号

Interface(インターフェース)2015年10月号