From c2cfa8820c111eb17126ef46625aa670bc884947 Mon Sep 17 00:00:00 2001 From: LeiJuntao <2606542098@qq.com> Date: Mon, 27 Apr 2026 15:19:21 +0800 Subject: [PATCH] =?UTF-8?q?w5=20=20=E5=88=86=E5=B1=82=E7=BB=83=E4=B9=A0?= =?UTF-8?q?=E8=AE=BE=E8=AE=A1?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- W5/ComputerTest.java | 60 ++++++++++++++++++++++++++++++++++++++++++++ W5/Shape1.java | 38 ++++++++++++++++++++++++++++ 2 files changed, 98 insertions(+) create mode 100644 W5/ComputerTest.java create mode 100644 W5/Shape1.java diff --git a/W5/ComputerTest.java b/W5/ComputerTest.java new file mode 100644 index 0000000..42ab65f --- /dev/null +++ b/W5/ComputerTest.java @@ -0,0 +1,60 @@ +// 1. 定义 USB 接口 +interface USB1 { + void open(); // 开启设备 + void close(); // 关闭设备 +} + +// 2. 鼠标类 实现 USB 接口 +class Mouse1 implements USB1 { + @Override + public void open() { + System.out.println("鼠标已连接:红光闪烁,准备就绪。"); + } + + @Override + public void close() { + System.out.println("鼠标已断开:红光熄灭。"); + } +} + +// 3. 键盘类 实现 USB 接口 +class Keyboard1 implements USB1 { + @Override + public void open() { + System.out.println("键盘已连接:指示灯闪烁,可以打字了。"); + } + + @Override + public void close() { + System.out.println("键盘已断开:指示灯熄灭。"); + } +} + +// 4. 电脑类 +class Computer1 { + // 核心方法:利用多态,参数是 USB1 接口类型 + // 这意味着它可以接收任何实现了 USB1 接口的对象(鼠标、键盘、U盘等) + public void useUSB(USB1 usb) { + System.out.println(">>> 电脑检测到设备插入..."); + usb.open(); // 调用具体设备的 open 方法 + usb.close(); // 调用具体设备的 close 方法 + System.out.println("-------------------------"); + } +} + +// 5. 测试类(主程序) +public class ComputerTest { + public static void main(String[] args) { + // 创建电脑对象 + Computer1 myPc = new Computer1(); + + // 创建具体的 USB 设备 + Mouse1 mouse = new Mouse1(); + Keyboard1 keyboard = new Keyboard1(); + + // 将设备插入电脑 + // 这里体现了多态:把子类对象(Mouse1)赋值给父接口引用(USB1) + myPc.useUSB(mouse); // 输出鼠标的行为 + myPc.useUSB(keyboard); // 输出键盘的行为 + } +} diff --git a/W5/Shape1.java b/W5/Shape1.java new file mode 100644 index 0000000..2b500f8 --- /dev/null +++ b/W5/Shape1.java @@ -0,0 +1,38 @@ +public class Shape1 { + public void draw() { + System.out.println("绘制一个图形"); + } + + // 静态方法,用于测试多态 + public static void drawShape(Shape1 s) { + s.draw(); + } + + public static void main(String[] args) { + System.out.println("--- 基础题测试 ---"); + + // 创建子类对象 + Circle1 c = new Circle1(); + Rectangle1 r = new Rectangle1(); + + // 调用测试方法,体现多态性 + drawShape(c); // 输出: 绘制一个圆形 + drawShape(r); // 输出: 绘制一个矩形 + } +} + +// 子类 Circle1,注意这里不要加 public +class Circle1 extends Shape1 { + @Override + public void draw() { + System.out.println("绘制一个圆形"); + } +} + +// 子类 Rectangle1,注意这里不要加 public +class Rectangle1 extends Shape1 { + @Override + public void draw() { + System.out.println("绘制一个矩形"); + } +}