You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
21 lines
919 B
21 lines
919 B
Shape类:定义一个Shape类(draw()方法),子类Circle、Rectangle重写draw()。编写一个方法,调用其draw()方法,并在main中测试。
|
|
|
|
Vehicle类:定义一个抽象父类vehicle,包含抽象方法run()。实现Car、Bicycle、Truck三个子类。在主方中创建Vehicle数组,存放不同车辆,遍历调用run()。
|
|
|
|
Al协助说明:
|
|
1.怎么在main方法中创建数组?
|
|
A:1. 创建父类类型数组,长度为3
|
|
Vehicle[] vehicles = new Vehicle[3];
|
|
// 2. 放入 3 个具体交通工具对象(多态)
|
|
vehicles[0] = new Car();
|
|
vehicles[1] = new Bicycle();
|
|
vehicles[2] = new Truck();
|
|
2.如何遍历数组?
|
|
写法 1:普通 for 循环
|
|
for (int i = 0; i < vehicles.length; i++) {
|
|
vehicles[i].run(); // 自动调用子类重写的run()
|
|
}
|
|
写法 2:增强 for 循环
|
|
for (Vehicle v : vehicles) {
|
|
v.run(); // 直接遍历每个元素,无需下标
|
|
}
|