抽象类

2016-03-25  本文已影响0人  曾刚

为什么存在抽象类

抽象类是将类共有的方法抽取出来,不同的方法声明为抽象类;这样新增一种类型时候只需要继承抽象类,实现抽象方法就可以了,降低了实现新类的难度。

使用抽象类需要注意的点

样例

// abstract 标记抽象类
public abstract class Employee {
    protected String name;
    protected int age;

    public String getName() {
        return name;
    }

    public int getAge() {
        return age;
    }

    public Employee(int age, String name) {
        this.age = age;
        this.name = name;
    }

    public Employee(){}

    public void play(){
        System.out.println(String.format("name: %s age: %s", this.name, this.age));
    }

    // 静态方法不能被继承类重写
    public static void jump(){
        System.out.println("jump ...");
    };

    // 标记为抽象方法
    protected abstract void remove(int duration);
}
public class User extends Employee {
    public String name;

    public User(String name) {
        super(21, "emp1");
        this.name = name;
    }

    @Override
    public void play() {
        System.out.println("play ..." + super.name);
    }

    @Override
    public void remove(int duration) {
        System.out.println("remove ..." + this.age);
    }

    public static void test(Employee emp){
        emp.play();
    }
    public static void main(String[] args) {
        Employee employee = new User("xx-yy");
        employee.remove(1);
        employee.play();
        employee.jump();

        test(employee);
    }
}
上一篇 下一篇

猜你喜欢

热点阅读