class Dog extends Pet {
private String color;
public Dog(String name, int age, int health) {
// super 超类/父类,调用的父类的构造方法
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;
}
}
多态:自类的对象可以当做父类来使用
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类型的参数,实际传的是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.有抽象方法的类是抽象类,抽象方法只有声明,没有实现
2.抽象类中既可以有抽象方法,也可以由普通方法
3.抽象类不能实例化,无法new一个对象
4.抽象类主要是为了被继承,子类必须实现里面的抽象方法,如果子类不是实现抽象方法子类也只能定义抽象方法