Javaで昆虫を動かす

概要

Insectインターフェースを昆虫クラスに実装する。昆虫の動作を確認する。

interface Insect {
    int legs = 6;

    void move();

    void eat();

    void cry();

}

class Grasshopper implements Insect {
    public Grasshopper() {
        System.out.println("キリギリスです。");
        System.out.println("昆虫です。足は" + Insect.legs + "本です。");
    }

    public void move() {
        System.out.println("後ろ足で跳ねます。");
    }

    public void eat() {
        System.out.println("雑食性です。");
    }

    public void cry() {
        System.out.println("ギーギー鳴きます。");
    }

    public String toString() {
        return "キリギリス";
    }
}

public class GrasshopperTest {
    public static void main(String[] args) {
        Insect gh = new Grasshopper();
        gh.move();
        gh.eat();
        gh.cry();
    }
}

実行結果

キリギリスです。
昆虫です。足は6本です。
後ろ足で跳ねます。
雑食性です。
ギーギー鳴きます。

昆虫はすごい (光文社新書)

昆虫はすごい (光文社新書)

昆虫はもっとすごい (光文社新書)

昆虫はもっとすごい (光文社新書)