2 changed files with 87 additions and 0 deletions
@ -0,0 +1,39 @@ |
|||||
|
// 图形父类
|
||||
|
class Shape { |
||||
|
public void draw() { |
||||
|
System.out.println("绘制图形"); |
||||
|
} |
||||
|
} |
||||
|
|
||||
|
// 圆形子类
|
||||
|
class Circle extends Shape { |
||||
|
@Override |
||||
|
public void draw() { |
||||
|
System.out.println("绘制圆形"); |
||||
|
} |
||||
|
} |
||||
|
|
||||
|
// 矩形子类
|
||||
|
class Rectangle extends Shape { |
||||
|
@Override |
||||
|
public void draw() { |
||||
|
System.out.println("绘制矩形"); |
||||
|
} |
||||
|
} |
||||
|
|
||||
|
// 测试主类
|
||||
|
public class ShapeTest { |
||||
|
|
||||
|
// 题目要求的方法
|
||||
|
public static void drawShape(Shape s) { |
||||
|
s.draw(); |
||||
|
} |
||||
|
|
||||
|
public static void main(String[] args) { |
||||
|
Shape c = new Circle(); |
||||
|
Shape r = new Rectangle(); |
||||
|
|
||||
|
drawShape(c); |
||||
|
drawShape(r); |
||||
|
} |
||||
|
} |
||||
@ -0,0 +1,48 @@ |
|||||
|
// 抽象父类 交通工具
|
||||
|
abstract class Vehicle { |
||||
|
// 抽象方法
|
||||
|
public abstract void run(); |
||||
|
} |
||||
|
|
||||
|
// 小汽车
|
||||
|
class Car extends Vehicle { |
||||
|
@Override |
||||
|
public void run() { |
||||
|
System.out.println("小汽车在公路上行驶"); |
||||
|
} |
||||
|
} |
||||
|
|
||||
|
// 自行车
|
||||
|
class Bike extends Vehicle { |
||||
|
@Override |
||||
|
public void run() { |
||||
|
System.out.println("自行车在慢慢骑行"); |
||||
|
} |
||||
|
} |
||||
|
|
||||
|
// 卡车
|
||||
|
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