定义生物类Live,(属性:name名称)它的两个子类分别是动物Animals(属性:color颜色)和植物Plants(属性:color颜色)。其中动物Animals的子类有Cow奶牛类和Sheep绵羊类,(属性:weight体重)。植物Plants类有Tree树类和Flowers类,(属性:height高度)。用程序定义他们之间的关系,要求:对属性进行封装。同时定义这些类的无参构造和有参构造。
时间: 2024-03-02 07:47:54 浏览: 19
以下对应的Java代码:
```
// Live类
public class Live {
private String name;
public Live() {}
public Live(String name) {
this.name = name;
}
public String getName() {
return name;
}
}
// Animals类
public class Animals extends Live {
private String color;
public Animals() {}
public Animals(String name, String color) {
super(name);
this.color = color;
}
public String getColor() {
return color;
}
}
// Cow类
public class Cow extends Animals {
private double weight;
public Cow() {}
public Cow(String name, String color, double weight) {
super(name, color);
this.weight = weight;
}
public double getWeight() {
return weight;
}
}
// Sheep类
public class Sheep extends Animals {
private double weight;
public Sheep() {}
public Sheep(String name, String color, double weight) {
super(name, color);
this.weight = weight;
}
public double getWeight() {
return weight;
}
}
// Plants类
public class Plants extends Live {
private String color;
public Plants() {}
public Plants(String name, String color) {
super(name);
this.color = color;
}
public String getColor() {
return color;
}
}
// Tree类
public class Tree extends Plants {
private double height;
public Tree() {}
public Tree(String name, String color, double height) {
super(name, color);
this.height = height;
}
public double getHeight() {
return height;
}
}
// Flowers类
public class Flowers extends Plants {
private double height;
public Flowers() {}
public Flowers(String name, String color, double height) {
super(name, color);
this.height = height;
}
public double getHeight() {
return height;
}
}
```
以上代码实现了`Live`作为父类,`Animals`和`Plants`作为子类,并且`Animals`有`Cow`和`Sheep`两个子类,`Plants`有`Tree`和`Flowers`两个子类。每个类都有自己的属性,同时对属性进行了封装,并且定义了无参构造和有参构造。