1 package javastudy.summary; 2 3 /** 4 * 父类Animal 5 * 在class的前面加上abstract,即声明成这样:abstract class Animal 6 * 这样Animal类就成了一个抽象类了 7 */ 8 abstract class Animal { 9 10 public String name; 11 12 public Animal(String name) { 13 this.name = name; 14 } 15 16 /** 17 * 抽象方法 18 * 这里只有方法的定义,没有方法的实现。 19 */ 20 public abstract void enjoy(); 21 22 } 23 24 /** 25 * 这里的子类Cat从抽象类Animal继承下来,自然也继承了Animal类里面声明的抽象方法enjoy(), 26 * 但子类Cat觉得自己去实现这个enjoy()方法也不合适,因此它把它自己也声明成一个抽象的类, 27 * 那么,谁去实现这个抽象的enjoy方法,谁继承了子类,那谁就去实现这个抽象方法enjoy()。 28 * @author gacl 29 * 30 */ 31 abstract class Cat extends Animal { 32 33 /** 34 * Cat添加自己独有的属性 35 */ 36 public String eyeColor; 37 38 public Cat(String n, String c) { 39 super(n);//调用父类Animal的构造方法 40 this.eyeColor = c; 41 } 42 } 43 44 /** 45 * 子类BlueCat继承抽象类Cat,并且实现了从父类Cat继承下来的抽象方法enjoy 46 * @author gacl 47 * 48 */ 49 class BlueCat extends Cat { 50 51 public BlueCat(String n, String c) { 52 super(n, c); 53 } 54 55 /** 56 * 实现了抽象方法enjoy 57 */ 58 @Override 59 public void enjoy() { 60 System.out.println("蓝猫叫..."); 61 } 62 63 } 64 65 /** 66 * 子类Dog继承抽象类Animal,并且实现了抽象方法enjoy 67 * @author gacl 68 * 69 */ 70 class Dog extends Animal { 71 /** 72 * Dog类添加自己特有的属性 73 */ 74 public String furColor; 75 76 public Dog(String n, String c) { 77 super(n);//调用父类Animal的构造方法 78 this.furColor = c; 79 } 80 81 @Override 82 public void enjoy() { 83 System.out.println("狗叫...."); 84 } 85 86 } 87 88 public class TestAbstract { 89 90 /** 91 * @param args 92 */ 93 public static void main(String[] args) { 94 95 /** 96 * 把Cat类声明成一个抽象类以后,就不能再对Cat类进行实例化了, 97 * 因为抽象类是残缺不全的,缺胳膊少腿的,因此抽象类不能被实例化。 98 */ 99 //Cat c = new Cat("Catname","blue"); 100 Dog d = new Dog("dogname","black"); 101 d.enjoy();//调用自己实现了的enjoy方法 102 103 BlueCat c = new BlueCat("BlueCatname","blue"); 104 c.enjoy();//调用自己实现了的enjoy方法 105 } 106 }