public abstract class Demo4Animal { private String name; private int health; private int love; public Demo4Animal() { super();//调用父类Object类里的无参构造方法 } public Demo4Animal(String name, int health, int love) { super();//调用父类Object类里的无参构造方法 this.name = name; this.health = health; this.love = love; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getHealth() { return health; } public void setHealth(int health) { this.health = health; } public int getLove() { return love; } public void setLove(int love) { this.love = love; } // 定义一个输出动物信息的方法 public void print() { System.out.println("动物昵称:" + this.name + ",健康值:" + this.health + ",亲密度:" + this.love); } //定义一个Animal去医院看病的方法 public abstract void toHospital(); /* * 抽象方法: * (1)使用abstract修饰的方法为抽象方法 * (2)抽象方法没有方法体,即不写花括号 * (3)抽象方法所在的类要声明为抽象类 * (4)子类必须重写父类中所有的抽象方法,如果不重写,子类也要定义成抽象类 * *抽象类: * (1)使用abstract修饰的类为抽象类 * (2)抽象类中可以有普通方法,也可以有抽象方法,也可以没有抽象方法 * (3)抽象类不能实例化,实例化没有任何意义 * */ }
public class Demo4Cat extends Demo4Animal{ private String color; public Demo4Cat() { super(); } public Demo4Cat(String name, int health, int love, String color) { super(name, health, love); this.color = color; } public String getColor() { return color; } public void setColor(String color) { this.color = color; } //重新定义父类里的print()方法 public void print(){ //输出宠物的所有信息 super.print(); System.out.println("宠物颜色:"+this.color); } @Override public void toHospital() { System.out.println("(猫)打针......"); this.setHealth(70); } //定义一个Cat类自己的方法 public void play(){ System.out.println("猫咪喜欢粘人,喜欢完球"); } }
public class Demo4Test { public static void main(String[] args) { // Animal animal = new Animal(); //抽象类不能实例化 //向上转型:父类的引用指向子类的实例----》 子---->父 Demo4Animal animal = new Demo4Cat("咪咪", 50, 80, "白色"); animal.toHospital(); //animal.play(); //父类的引用不能调用子类里独有的方法,要想使用子类特有的方法,需要将父类引用转换成子类对象 //instanceof:判断某一个引用指向的是哪一个实例 //向下转型(引用数据类型的强制转换):子类的引用指向父类的对象名---->父-->子 Demo4Cat cat = (Demo4Cat)animal; cat.play(); } }