采用抽象的思想编写猫和狗的案例在测试类中进行测试【需求】:分析猫类和狗类找到猫类和狗类当中的共性内容抽取出一个父类用继承的方式编写一个父类Animal 两个子类猫类Cat和狗类Dog;
// Animal类 public abstract class Animal { private String name; private int age; private String color;
public Animal(String name, int age, String color) {
this.name = name;
this.age = age;
this.color = color;
}
public abstract void shout();
public String getName() {
return name;
}
public int getAge() {
return age;
}
public String getColor() {
return color;
}
}
// Cat类 public class Cat extends Animal { public Cat(String name, int age, String color) { super(name, age, color); }
@Override
public void shout() {
System.out.println("喵喵喵");
}
}
// Dog类 public class Dog extends Animal { public Dog(String name, int age, String color) { super(name, age, color); }
@Override
public void shout() {
System.out.println("汪汪汪");
}
}
// 测试类 public class Test { public static void main(String[] args) { Animal animal1 = new Cat("小花", 2, "白色"); Animal animal2 = new Dog("小黑", 3, "黑色");
System.out.println(animal1.getName() + "的叫声:");
animal1.shout();
System.out.println(animal2.getName() + "的叫声:");
animal2.shout();
}
原文地址: https://www.cveoy.top/t/topic/em4e 著作权归作者所有。请勿转载和采集!