什么是抽象方法

用abstract关键字来修饰的方法抽象方法

抽象方法是只需要声明不需要实现

抽象方法必需被重写否则会报错。

用abstract关键字来修饰


什么是抽象类
用abstract关键字来修饰的类叫抽象类

含有抽象方法的抽象类叫做抽象类,抽象类必需本继承,抽象方法也必需被重写

抽象类不能被实例化 抽象方法是只需要声明不需要实现

 

  1. abstract class Animal { 
  2.   private String name; 
  3.   Animal(String name) {this.name = name;} 
  4.   /* 
  5.   public void enjoy(){ 
  6.     System.out.println("叫声......"); 
  7.   } 
  8.   */ 
  9.   public abstract void enjoy(); 
  10.  
  11. abstract class Cat extends Animal { 
  12.   private String eyesColor; 
  13.   Cat(String n,String c) {super(n); eyesColor = c;} 
  14.   /* 
  15.   public void enjoy() { 
  16.     System.out.println("猫叫声......"); 
  17.   } 
  18.   */ 
  19.   //public abstract void enjoy(); 
  20.  
  21. class Dog extends Animal { 
  22.   private String furColor; 
  23.   Dog(String n,String c) {super(n); furColor = c;} 
  24.   
  25.   public void enjoy() { 
  26.     System.out.println("狗叫声......"); 
  27.   } 
  28.  
  29. class Bird extends Animal { 
  30.      Bird() { 
  31.          super("bird"); 
  32.      } 
  33.      public void enjoy() { 
  34.     System.out.println("鸟叫声......"); 
  35.   } 
  36.  
  37. class Lady { 
  38.     private String name; 
  39.     private Animal pet; 
  40.     Lady(String name,Animal pet) { 
  41.         this.name = name; this.pet = pet; 
  42.     } 
  43.     public void myPetEnjoy(){pet.enjoy();} 
  44.  
  45. public class Test { 
  46.     public static void main(String args[]){ 
  47.         Cat c = new Cat("catname","blue"); 
  48.         Dog d = new Dog("dogname","black"); 
  49.         Bird b = new Bird(); 
  50.         Lady l1 = new Lady("l1",c); 
  51.         Lady l2 = new Lady("l2",d); 
  52.         Lady l3 = new Lady("l3",b); 
  53.        //l1.myPetEnjoy(); 
  54.         l2.myPetEnjoy(); 
  55.         l3.myPetEnjoy(); 
  56.     }