定义一个植物类,有3个属性:高度,颜色,重量。请将属性定义为私有的,并生成get和set方法。
3.3)找到这3棵树中最高的树并输出。
植物类属性定义正确、get和set方法正确
树类定义正确、继承语法正确。树类属性定义正确
树类的构造方法定义正确
实例化树对象正确输出树信息
正确输出最高的树
代码如下,希望对您有所帮助,采纳一下吧
public class Plant {
//定义高度、颜色、重量
private double height;
private String color;
private double weight;
//无参构造方法
public Plant() {
}
//有参构造方法
public Plant(double height, String color, double weight) {
this.height = height;
this.color = color;
this.weight = weight;
}
public double getHeight() {
return height;
}
public void setHeight(double height) {
this.height = height;
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
public double getWeight() {
return weight;
}
public void setWeight(double weight) {
this.weight = weight;
}
}
public class Tree extends Plant{
//定义树干、树叶属性
private String treeTrunk;
private String leaf;
//定义构造方法
public Tree(double height, String color, double weight, String treeTrunk, String leaf) {
super(height, color, weight);
this.treeTrunk = treeTrunk;
this.leaf = leaf;
}
public String getTreeTrunk() {
return treeTrunk;
}
public void setTreeTrunk(String treeTrunk) {
this.treeTrunk = treeTrunk;
}
public String getLeaf() {
return leaf;
}
public void setLeaf(String leaf) {
this.leaf = leaf;
}
//定义输出树信息的方法
public void outputTreeInfo() {
System.out.println("树高:" + this.getHeight() + "颜色:" +
this.getColor() + "重量:" + this.getWeight() +
"树干:" + this.treeTrunk + "树叶:" + this.leaf);
}
}
//测试类
public class Test {
public static void main(String[] args) {
//定义三棵树对象
Tree tree1 = new Tree(20.0, "黄色", 100, "黄色树干", "黄色树叶");
Tree tree2 = new Tree(40.0, "白色", 100, "白色树干", "白色树叶");
Tree tree3 = new Tree(25.1, "绿色", 100, "绿色树干", "绿色树叶");
//输出三棵树的信息
tree1.outputTreeInfo();
tree2.outputTreeInfo();
tree3.outputTreeInfo();
//比较三棵树的高度
double height = tree1.getHeight();
String tree = "tree1";
if (height < tree2.getHeight()) {
height = tree2.getHeight();
tree = "tree2";
}
if (height < tree3.getHeight()) {
height = tree3.getHeight();
tree = "tree3";
}
//输出最高树的信息
System.out.println("最高的树:");
if ("tree1".equals(tree)) {
tree1.outputTreeInfo();
}
if ("tree2".equals(tree)) {
tree2.outputTreeInfo();
}
if ("tree3".equals(tree)) {
tree3.outputTreeInfo();
}
}
}
运行结果如下