Java-abstract(抽象)、final、static

来源:互联网 发布:matlab编程与工程应用 编辑:程序博客网 时间:2024/06/07 05:44

抽象类和抽象方法(abstract)

  • 抽象类不能被实例化,只能被继承
  • 抽象类中不一定都是抽象方法
  • 抽象类中的抽象方法必须被非抽象子类实现
  • 抽象方法必须放在抽象类内
  • 抽象方法没有方法体
//抽象类abstract class Instrument {    private String brand; //品牌    private double weight;//重量    public Instrument() {        super();    }    public Instrument(String brand, double weight) {        super();        this.brand = brand;        this.weight = weight;    }    //抽象方法    public abstract void play();    //get、set方法略,下同}class Piano extends Instrument {    protected double size;//尺寸    public Piano() {        super();    }    public Piano(String brand, double weight, double size) {        super(brand, weight);        this.size = size;    }    @Override    public void play(){        System.out.println("演奏钢琴");    }}class Violin extends Instrument {    protected double length;    public Violin() {        super();    }    public Violin(String brand, double weight, double length) {        super(brand, weight);        this.length = length;    }    @Override    public void play(){        System.out.println("演奏小提琴");    }}

final

  • final修饰的类不能被继承;
  • final修饰的方法不能被重写;
  • final修饰的属性值不能被修改。

static

  • static可以用来修饰属性、方法和代码块
  • static修饰的属性和方法称为类属性(类变量)、类方法(区别于成员属性、成员方法)
  • 父类和子类中都有static变量,初始化顺序:
    1.父类static变量/代码块 初始化
    2.子类static变量/代码块 初始化
    3.父类构造方法
    4.子类构造方法
原创粉丝点击