定义一个动物类Animal为抽象类:成员变量weight、age、成员函数getAge、getWeight、setAgeint、setWeightint、叫声meow。根据Animal类派生出猫Cat类猫所具有的成员变量weight、age、color成员函数getAge、getWeight、setAgeint、setWeightint、setColorchar、getColor、run、meow
abstract class Animal {
protected int weight;
protected int age;
public Animal(int weight, int age) {
this.weight = weight;
this.age = age;
}
public int getAge() {
return age;
}
public int getWeight() {
return weight;
}
public void setAge(int age) {
this.age = age;
}
public void setWeight(int weight) {
this.weight = weight;
}
public abstract void meow();
}
class Cat extends Animal {
private String color;
public Cat(int weight, int age, String color) {
super(weight, age);
this.color = color;
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
public void run() {
System.out.println("I am running.");
}
@Override
public void meow() {
System.out.println("Meow~");
}
}
public class Main {
public static void main(String[] args) {
Cat cat = new Cat(5, 2, "black");
System.out.println("Age: " + cat.getAge());
System.out.println("Color: " + cat.getColor());
cat.meow();
}
}
``
原文地址: https://gggwd.com/t/topic/hs97 著作权归作者所有。请勿转载和采集!