class Dog extends Pet {
private String color;
public Dog(String name, int age, int health) {
// super 超類/父類,調(diào)用的父類的構(gòu)造方法
super(name, age, health);
}
public Dog(String name, int age, int health, String color) {
super(name, age, health);
this.color = color;
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
}
多態(tài):自類的對(duì)象可以當(dāng)做父類來(lái)使用
public class Demo04 {
// 寵物看病的方法
public static void doctor_shenyi(Pet pet){//傳Pet 或Pet的子類
if(pet.getHealth()<50){
System.out.println("打針");
pet.setHealth(pet.getHealth()+20);
}else{
System.out.println("按摩");
pet.setHealth(pet.getHealth()+2);
}
}
public static void main(String[] args) {
Dog dog =new Dog("小白",3,40); doctor(dog); doctor_shenyi(dog);//方法的定義的是Pet類型的參數(shù),實(shí)際傳的是Dog的類型
System.out.println(dog.getHealth());
Pet pet = new Pet("小小",2,50); doctor_shenyi(pet);
Cat cat = new Cat("加菲",1,80); doctor_shenyi(cat);
TaiDi taiDi = new TaiDi("泰迪",2,70,"白色"); doctor_shenyi(taiDi); doctor(taiDi);
}
}
class Cat extends Pet{
public Cat(String name, int age, int health) {
super(name, age, health);
}
}
抽象類:abstract 修飾
1.有抽象方法的類是抽象類,抽象方法只有聲明,沒(méi)有實(shí)現(xiàn)
2.抽象類中既可以有抽象方法,也可以由普通方法
3.抽象類不能實(shí)例化,無(wú)法new一個(gè)對(duì)象
4.抽象類主要是為了被繼承,子類必須實(shí)現(xiàn)里面的抽象方法,如果子類不是實(shí)現(xiàn)抽象方法子類也只能定義抽象方法