java:定义一个昆虫类insect,包括属性name,size,color,定义其有参构造方法;生成成员变量的get和set方法;定义run方法viid run(Insect a)打印输出谁在跑,接收参数为Insect类型;在main函数测试该类new一个实例对象i,调用run方法,然后打印输出i的name,size,color)
时间: 2023-07-16 14:14:30 浏览: 87
Java代码如下:
```java
public class Insect {
private String name;
private double size;
private String color;
// 有参构造方法
public Insect(String name, double size, String color) {
this.name = name;
this.size = size;
this.color = color;
}
// 成员变量的get和set方法
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getSize() {
return size;
}
public void setSize(double size) {
this.size = size;
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
// run方法
public void run(Insect a) {
System.out.println(a.getName() + " is running.");
}
public static void main(String[] args) {
// 创建实例对象i
Insect i = new Insect("Bee", 2.5, "Yellow");
// 调用run方法
i.run(i);
// 打印输出i的name、size、color
System.out.println("Name: " + i.getName());
System.out.println("Size: " + i.getSize());
System.out.println("Color: " + i.getColor());
}
}
```
输出结果如下:
```
Bee is running.
Name: Bee
Size: 2.5
Color: Yellow
```
阅读全文