7 changed files with 91 additions and 0 deletions
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
@ -0,0 +1,45 @@ |
|||||
|
// 1. 定义父类 Shape
|
||||
|
class Shape { |
||||
|
// 父类的 draw() 方法,子类可以重写
|
||||
|
public void draw() { |
||||
|
System.out.println("绘制通用图形"); |
||||
|
} |
||||
|
} |
||||
|
|
||||
|
// 2. 定义子类 Circle,继承 Shape,重写 draw()
|
||||
|
class Circle extends Shape { |
||||
|
@Override |
||||
|
public void draw() { |
||||
|
System.out.println("绘制圆形 ⭕"); |
||||
|
} |
||||
|
} |
||||
|
|
||||
|
// 3. 定义子类 Rectangle,继承 Shape,重写 draw()
|
||||
|
class Rectangle extends Shape { |
||||
|
@Override |
||||
|
public void draw() { |
||||
|
System.out.println("绘制矩形 🟦"); |
||||
|
} |
||||
|
} |
||||
|
|
||||
|
// 4. 主类,包含 drawShape 方法和 main 测试方法
|
||||
|
public class ShapeTest { |
||||
|
// 多态方法:接收 Shape 类型参数,调用其 draw()
|
||||
|
public static void drawShape(Shape s) { |
||||
|
s.draw(); // 动态绑定:实际调用传入对象的 draw()
|
||||
|
} |
||||
|
|
||||
|
public static void main(String[] args) { |
||||
|
// 测试1:传入 Circle 对象
|
||||
|
Shape circle = new Circle(); |
||||
|
drawShape(circle); |
||||
|
|
||||
|
// 测试2:传入 Rectangle 对象
|
||||
|
Shape rectangle = new Rectangle(); |
||||
|
drawShape(rectangle); |
||||
|
|
||||
|
// 测试3:直接传入对象(更简洁)
|
||||
|
drawShape(new Circle()); |
||||
|
drawShape(new Rectangle()); |
||||
|
} |
||||
|
} |
||||
@ -0,0 +1,46 @@ |
|||||
|
// 抽象父类Vehicle
|
||||
|
abstract class Vehicle { |
||||
|
public abstract void run(); |
||||
|
} |
||||
|
|
||||
|
// 子类Car
|
||||
|
class Car extends Vehicle { |
||||
|
@Override |
||||
|
public void run() { |
||||
|
System.out.println("小汽车在公路上行驶"); |
||||
|
} |
||||
|
} |
||||
|
|
||||
|
// 子类Bike
|
||||
|
class Bike extends Vehicle { |
||||
|
@Override |
||||
|
public void run() { |
||||
|
System.out.println("自行车在非机动车道行驶"); |
||||
|
} |
||||
|
} |
||||
|
|
||||
|
// 子类Truck
|
||||
|
class Truck extends Vehicle { |
||||
|
@Override |
||||
|
public void run() { |
||||
|
System.out.println("卡车在货运道路行驶"); |
||||
|
} |
||||
|
} |
||||
|
|
||||
|
// 主类
|
||||
|
public class VehicleTest { |
||||
|
public static void main(String[] args) { |
||||
|
// 创建Vehicle数组,存放不同车辆
|
||||
|
Vehicle[] vehicles = { |
||||
|
new Car(), |
||||
|
new Bike(), |
||||
|
new Truck() |
||||
|
}; |
||||
|
|
||||
|
// 遍历调用run()
|
||||
|
System.out.println("=== 车辆行驶测试 ==="); |
||||
|
for (Vehicle v : vehicles) { |
||||
|
v.run(); |
||||
|
} |
||||
|
} |
||||
|
} |
||||
Loading…
Reference in new issue