java之抽象类

一、抽象方法

1、抽象方法的定义

  • abstract关键字声明,没有方法体的方法称为抽象方法
    例如:public abstract void print();

2、抽象方法的作用

  • 规定了子类中必须有这样一个方法,而具体的方法实现
    由子类决定。

二、抽象类

1、抽象类的定义

  • 包含一个或多个抽象方法的类本身必须被声明为抽象的。
  • 抽象类使用abstract关键字声明
  • 抽象类不能实例化

2、抽象类的扩展

  • 1、在子类中保留抽象类中的部分或所有抽象方法仍未实现,这样就必须将子类也声明为抽象类。
  • 2、将所有抽象方法实现,这样子类就不是抽象类了。

3、示例代码

abstract class Person {
    private String name = null;
    private String major = null;
    public void setName(String name) {
        this.name = name;
    }
    public String getName() {
        return this.name;
    }
    public abstract String getDecription();
}
class Student extends Person{
    public String getDecription() {
        return "this is student";
    }
}
class Emplyee extends Person {
    public String getDecription() {
        return "this is emplyee";
    }
}
public class App {
    public static void main(String[] args) {
        Student student = new Student();
        student.setName("tangxin");
        System.out.println(student.getName());
        System.out.println(student.getDecription());
        Emplyee emplyee = new Emplyee();
        emplyee.setName("zhanggang");
        System.out.println(emplyee.getName());
        System.out.println(emplyee.getDecription());
        Person person = new Student();

    }
}

三、抽象类之模板方法

abstract class Person {
    abstract public void action();
    abstract public void eat();
    //模板方法
    public void run() {
        this.action();
        this.eat();
    }
}
class Student extends Person{
    public void action() {
        System.out.println("study");
    }
    public void eat() {
        System.out.println("eat beef");
    }
}
class Empyee extends Person {
    public void action() {
        System.out.println("work");
    }
    public void eat() {
        System.out.println("eat mutton");
    }
}
public class App {
    public static void main(String[] args) {
        Student student = new Student();
        student.run();
        Empyee empyee = new Empyee();
        empyee.run();
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值