5 changed files with 78 additions and 0 deletions
@ -0,0 +1,22 @@ |
|||||
|
/*定义一个抽象类draw*/ |
||||
|
abstract class draw{ |
||||
|
public abstract void draw(); |
||||
|
} |
||||
|
class circle extends draw{ |
||||
|
public void draw(){ |
||||
|
System.out.println("画一个圆形"); |
||||
|
} |
||||
|
} |
||||
|
class retangle extends draw{ |
||||
|
public void draw(){ |
||||
|
System.out.println("画一个矩形"); |
||||
|
} |
||||
|
} |
||||
|
class Main{ |
||||
|
public static void main (String args[]){ |
||||
|
draw d1=new circle(); |
||||
|
draw d2=new retangle(); |
||||
|
d1.draw(); |
||||
|
d2.draw(); |
||||
|
} |
||||
|
} |
||||
|
After Width: | Height: | Size: 417 KiB |
|
After Width: | Height: | Size: 309 KiB |
@ -0,0 +1,35 @@ |
|||||
|
class Vehicle { |
||||
|
public void run() { |
||||
|
|
||||
|
} |
||||
|
} |
||||
|
class Car extends Vehicle{ |
||||
|
@Override |
||||
|
public void run(){ |
||||
|
System.out.println("汽车启动了~"); |
||||
|
} |
||||
|
} |
||||
|
class Bicycle extends Vehicle{ |
||||
|
@Override |
||||
|
public void run(){ |
||||
|
System.out.println("自行车启动了~"); |
||||
|
} |
||||
|
} |
||||
|
class Truck extends Vehicle{ |
||||
|
@Override |
||||
|
public void run(){ |
||||
|
System.out.println("卡车启动了~"); |
||||
|
} |
||||
|
} |
||||
|
public class Main { |
||||
|
static void main(String[] args) { |
||||
|
Vehicle[] vehicles = new Vehicle[3]; |
||||
|
vehicles[0] = new Car(); |
||||
|
vehicles[1] = new Bicycle(); |
||||
|
vehicles[2] = new Truck(); |
||||
|
for (int i = 0; i < 3; i++) { |
||||
|
Vehicle v = vehicles[i]; |
||||
|
v.run(); |
||||
|
} |
||||
|
} |
||||
|
} |
||||
@ -0,0 +1,21 @@ |
|||||
|
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(); // 直接遍历每个元素,无需下标 |
||||
|
} |
||||
Loading…
Reference in new issue