含有抽象方法的類叫做抽象類,但抽象類可以不含有抽象方法,也就是說抽象方法是抽象類的充分不必要條件。
我們寫一個(gè)抽象類的小例子,看看它的特點(diǎn):首先我們定義一個(gè)人的抽象類,里面有一個(gè)抽象方法print,然后學(xué)生類和工人類分別去繼承人這個(gè)類,此時(shí)必須要把人這個(gè)類中的抽象方法給覆蓋掉,最后我們調(diào)用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()+" 成績(jī):"+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()+" 成績(jī):"+this.getMoney()+"  今天掙了大錢";
 }
}


public class Abstract {

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

}

運(yùn)行結(jié)果是:


這個(gè)例子體現(xiàn)了類可以向上轉(zhuǎn)型的特性和類的多態(tài)性,調(diào)用同一個(gè)print方法卻有不同的輸出結(jié)果。