Dotcpp  /  试卷列表  /  Java  /  题目 8057

开发可以被计算机识别的各种U盘的接口程序。(1)定义一

开发可以被计算机识别的各种U盘的接口程序。

(1)定义一个接口IUSB,接口中有一个方法void speed()

(2)要求用两个类来实现该接口

(3)编写一个主类Compuer,主类Computer中要求有一个方法getspeed(),该方法的参数是“接口”类型,创建Computer的对象,调用此方法来验证接口作为方法的参数的使用方式。

答案
// (1) 定义 IUSB 接口
interface IUSB {
    void speed();
}

// (2) 用两个类实现该接口:金士顿U盘
class KingstonUSB implements IUSB {
    @Override
    public void speed() {
        System.out.println("金士顿U盘的读写速度为 3.0");
    }
}

// (2) 用两个类实现该接口:闪迪U盘
class SanDiskUSB implements IUSB {
    @Override
    public void speed() {
        System.out.println("闪迪U盘的读写速度为 3.1");
    }
}

// (3) 主类 Computer,getspeed() 参数为接口类型
class Computer {
    public void getspeed(IUSB usb) {
        usb.speed();
    }
}

// 测试主类
public class TestUSB {
    public static void main(String[] args) {
        // 创建 Computer 对象
        Computer computer = new Computer();

        // 创建不同的 U 盘对象,传入 Computer 的 getspeed() 方法
        IUSB kingston = new KingstonUSB();
        IUSB sandisk = new SanDiskUSB();

        // 验证接口作为方法参数的使用方式
        computer.getspeed(kingston);
        computer.getspeed(sandisk);
    }
}

题目信息

题号:8057
题型:简答题
知识点:Java
难度:普通