java 程序定义一个动物类(Animal)。属性(age、weight);方法(叫meow)、吃eat()、设置年龄setAge(),得到年龄getAge()等。然后再派生出两个子类狗(Dog)和奶牛(Cow),再根据各自特性添加成员变量和成员方法。
时间: 2023-06-19 20:03:58 浏览: 133
以下是 Java 代码实现:
```
public class Animal {
private int age;
private double weight;
public Animal(int age, double weight) {
this.age = age;
this.weight = weight;
}
public void meow() {
System.out.println("Animal meowing...");
}
public void eat() {
System.out.println("Animal eating...");
}
public void setAge(int age) {
this.age = age;
}
public int getAge() {
return age;
}
}
public class Dog extends Animal {
private String breed;
public Dog(int age, double weight, String breed) {
super(age, weight);
this.breed = breed;
}
public void bark() {
System.out.println("Dog barking...");
}
public String getBreed() {
return breed;
}
}
public class Cow extends Animal {
private int milkProduction;
public Cow(int age, double weight, int milkProduction) {
super(age, weight);
this.milkProduction = milkProduction;
}
public void moo() {
System.out.println("Cow mooing...");
}
public int getMilkProduction() {
return milkProduction;
}
}
```
在这个例子中,Animal 类有两个属性 age 和 weight,以及三个方法 meow、eat 和 setAge/getAge。Dog 类和 Cow 类都继承了 Animal 类,并添加了自己的属性和方法。Dog 类添加了 breed 属性和 bark 方法,Cow 类添加了 milkProduction 属性和 moo 方法。这个例子展示了继承和多态的基本概念。
阅读全文