什么是抽象方法
用abstract关键字来修饰的方法抽象方法
抽象方法是只需要声明不需要实现
抽象方法必需被重写否则会报错。
用abstract关键字来修饰
什么是抽象类
用abstract关键字来修饰的类叫抽象类
含有抽象方法的抽象类叫做抽象类,抽象类必需本继承,抽象方法也必需被重写
抽象类不能被实例化 抽象方法是只需要声明不需要实现
- abstract class Animal {
- private String name;
- Animal(String name) {this.name = name;}
- /*
- public void enjoy(){
- System.out.println("叫声......");
- }
- */
- public abstract void enjoy();
- }
- abstract class Cat extends Animal {
- private String eyesColor;
- Cat(String n,String c) {super(n); eyesColor = c;}
- /*
- public void enjoy() {
- System.out.println("猫叫声......");
- }
- */
- //public abstract void enjoy();
- }
- class Dog extends Animal {
- private String furColor;
- Dog(String n,String c) {super(n); furColor = c;}
- public void enjoy() {
- System.out.println("狗叫声......");
- }
- }
- class Bird extends Animal {
- Bird() {
- super("bird");
- }
- public void enjoy() {
- System.out.println("鸟叫声......");
- }
- }
- class Lady {
- private String name;
- private Animal pet;
- Lady(String name,Animal pet) {
- this.name = name; this.pet = pet;
- }
- public void myPetEnjoy(){pet.enjoy();}
- }
- public class Test {
- public static void main(String args[]){
- Cat c = new Cat("catname","blue");
- Dog d = new Dog("dogname","black");
- Bird b = new Bird();
- Lady l1 = new Lady("l1",c);
- Lady l2 = new Lady("l2",d);
- Lady l3 = new Lady("l3",b);
- //l1.myPetEnjoy();
- l2.myPetEnjoy();
- l3.myPetEnjoy();
- }
- }