[Java] 抽象类

抽象类
 *1 用abstract 关键字来修饰一个类时,这个类叫做抽象类。用abstract修饰方法时,该方法叫做抽象方法。
 *2 含有抽象方法的类必须声明为抽象类,抽象类必须被继承,抽象方法必须被重写
 *3 抽象类不能被实例化
 *4 抽象方法只需声明,而不需要实现。
 other : 调整格式快捷键 Ctrl+Shift+f , 另外格式可以自己设定
package com.bjsxt.chap03.abstrac;

abstract class Animal {
    private String name;

    Animal(String name) {
        this.name = name;
    }

    public abstract void enjoy();
}

abstract class Cat extends Animal {
    private String eyesColor;

    Cat(String n, String c) {
        super(n);
        eyesColor = c;
    }
}

class Dog extends Animal {
    private String furColor;

    Dog(String n, String c) {
        super(n);
        furColor = c;
    }

    public void enjoy() {
        System.out.println("狗叫声......");
    }
}

class Bird extends Animal {
    Bird() {
        super("bird");
    }

    public void enjoy() {
        System.out.println("鸟叫声......");
    }
}

class Lady {
    private String name;
    private Animal pet;

    Lady(String name, Animal pet) {
        this.name = name;
        this.pet = pet;
    }

    public void myPetEnjoy() {
        pet.enjoy();
    }
}

public class Test {
    public static void main(String args[]) {
        //Cat c = new Cat("catname", "blue");  error!
        Dog d = new Dog("dogname", "black");
        Bird b = new Bird();

        Lady l2 = new Lady("l2", d);
        Lady l3 = new Lady("l3", b);

        l2.myPetEnjoy();
        l3.myPetEnjoy();
    }
}

posted @ 2013-11-24 11:03  小尼人00  阅读(163)  评论(0编辑  收藏  举报