java如何生成代码(1)设计一个交通工具类,包含属性:品牌、颜色、最高时速,包含方法:驾驶、显示基本信息。 (2)设计3个子类:汽车、飞机、轮船。 (3)在测试类中,分别调用3个子类的驾驶的方法、显示基本信息的方法
时间: 2024-05-11 13:14:45 浏览: 15
Java可以使用模板引擎来生成代码,常用的模板引擎包括Freemarker、Velocity等。我们可以提前准备好交通工具类的模板代码,通过填充模板中的参数,生成相应的类代码。
下面是交通工具类的模板代码:
```
public class ${brand} {
private String color;
private double maxSpeed;
public ${brand}(String color, double maxSpeed) {
this.color = color;
this.maxSpeed = maxSpeed;
}
public void drive() {
System.out.println("Driving ${brand}...");
}
public void showInfo() {
System.out.println("Brand: ${brand}");
System.out.println("Color: " + color);
System.out.println("Max speed: " + maxSpeed);
}
}
```
我们可以通过替换`${brand}`,来生成汽车、飞机、轮船等不同的子类代码。下面是相应的测试代码:
```
public class Test {
public static void main(String[] args) {
Car car = new Car("Toyota", "Red", 180.0);
car.drive();
car.showInfo();
Plane plane = new Plane("Boeing", "White", 900.0);
plane.drive();
plane.showInfo();
Ship ship = new Ship("Cruise", "Blue", 50.0);
ship.drive();
ship.showInfo();
}
}
```
运行结果如下:
```
Driving Toyota...
Brand: Toyota
Color: Red
Max speed: 180.0
Driving Boeing...
Brand: Boeing
Color: White
Max speed: 900.0
Driving Cruise...
Brand: Cruise
Color: Blue
Max speed: 50.0
```
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)