含有抽象方法的類叫做抽象類,但抽象類可以不含有抽象方法,也就是說抽象方法是抽象類的充分不必要條件。
我們寫一個抽象類的小例子,看看它的特點:首先我們定義一個人的抽象類,里面有一個抽象方法print,然后學生類和工人類分別去繼承人這個類,此時必須要把人這個類中的抽象方法給覆蓋掉,最后我們調用say方法將print方法打印出來。
下面附例子:

abstract class Person{
 private String name;
 private int age;
 public Person(String name,int age){
  this.setName(name);
  this.setAge(age);
 }
 public String getName() {
  return name;
 }
 public void setName(String name) {
  this.name = name;
 }
 public int getAge() {
  return age;
 }
 public void setAge(int age) {
  this.age = age;
 }
 public void say(){
  System.out.println(this.print());
 }
 public abstract String print();
}


class Student extends Person{
 private int score;
 public Student(String name,int age,int score){
  super(name,age);
  this.setScore(score);
 }
 public int getScore() {
  return score;
 }
 public void setScore(int score) {
  this.score = score;
 }
 public String print(){
  return "姓名:"+this.getName()+" 年齡:"+this.getAge()+" 成績:"+this.getScore()+"  今天考了高分";
 }
}


class Worker extends Person{
 private int money;
 public Worker(String name,int age,int money){
  super(name,age);
  this.setMoney(money);
 }
 public int getMoney() {
  return money;
 }
 public void setMoney(int money) {
  this.money = money;
 }
 public String print(){
  return "姓名:"+this.getName()+" 年齡:"+this.getAge()+" 成績:"+this.getMoney()+"  今天掙了大錢";
 }
}


public class Abstract {

 public static void main(String[] args) {
  Person person1 = new Student("小強",21,89);
  Person person2 = new Worker("老李",45,2000);
  person1.say();
  person2.say();
 }

}

運行結果是:


這個例子體現了類可以向上轉型的特性和類的多態性,調用同一個print方法卻有不同的輸出結果。