為什么存在抽象類
抽象類是將類共有的方法抽取出來,不同的方法聲明為抽象類渺鹦;這樣新增一種類型時(shí)候只需要繼承抽象類,實(shí)現(xiàn)抽象方法就可以了毅厚,降低了實(shí)現(xiàn)新類的難度。
使用抽象類需要注意的點(diǎn)
- 抽象修飾符 abstract
- 抽象類不能被實(shí)現(xiàn)
- 成員變量祠锣,方法跟普通類一樣
- 如果一個(gè)類含有抽象方法那么必須聲明為抽象類
- 繼承抽象類的類必須實(shí)現(xiàn)抽象方法
- 類與抽象類成員變量重疊的情況下訪問抽象變量方式:super.name
樣例
// abstract 標(biāo)記抽象類
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));
}
// 靜態(tài)方法不能被繼承類重寫
public static void jump(){
System.out.println("jump ...");
};
// 標(biāo)記為抽象方法
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);
}
}