抽象类如何创建对象 用多态的i形式创建对象
如果创建一个新的dog类,要么也要重写抽象方法,要么就需要把dog变成抽象类
package com.cn;
public class Animaldemo {
public static void main(String[] args) {
//抽象类如何创建对象 用多态的i形式创建对象
// 如果创建一个新的dog类,要么也要重写抽象方法,要么就需要把dog变成抽象类
// 成员变量
Animal animal = new Cat();
animal.setAge(45);
animal.setName("修猫");
animal.eat();
animal.show();
System.out.println(animal.getAge()+" "+animal.getName());
Animal animal1 = new Dog();
animal1.setAge(18);
animal1.setName("修勾");
animal1.eat();
animal1.show();
System.out.println(animal1.getAge()+" "+animal1.getName());
}
}
package com.cn;
//一样的类一样的方法吧abstact 抽象类里可以有不抽象的方法
public abstract class Animal {
private String name;
private int age;
public Animal() {
}
public Animal(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public abstract void eat();
public abstract void show();
}
package com.cn;
public class Cat extends Animal{
public Cat() {
}
public Cat(String name,int age) {
super(name,age);
}
public void show(){
System.out.println("修猫飞飞");
}
public void eat(){
//重学方法
System.out.println("eat fish");
}
}
package com.cn;
public class Dog extends Animal {
public Dog() {
}
public Dog(String name, int age) {
super(name, age);
}
public void show(){
System.out.println("修勾飞飞");
}
public void eat(){
System.out.println("dog eat meat");
}
}