天天看点

Java面向抽象编程-接口

题目描述

开放型题目:

设计一个笔记本电脑类,属性随意,并且进行属性私有化,对外提供公开的set和get方法。

设计一个可插拔的接口:InsertDrawable,该接口有什么方法自行定义。

设计一个鼠标类,实现InsertDrawable接口,并实现方法。

设计一个键盘类,实现InsertDrawable接口,并实现方法。

设计一个显示器类,实现InsertDrawable接口,并实现方法。

设计一个打印机类,实现InsertDrawable接口,并实现方法。

在“笔记本电脑类”中有一个InsertDrawable接口属性,可以让笔记本

电脑可插拔鼠标、键盘、显示器、打印机等。

编写测试程序,创建多个对象,演示接口的作用。

实现效果

拔插鼠标!

Java代码

public class Homework2101 {
    public static void main(String[] args) {
        Mouse m = new Mouse();
        Computer c = new Computer("惠普",1.5,m);
        c.printInfo();
    }
}
class Computer{
    //电脑品牌
    private String brand;
    //电脑重量
    private double weight;
    //接口属性
    private InsertDrawable i;

    public String getBrand() {
        return brand;
    }

    public void setBrand(String brand) {
        this.brand = brand;
    }

    public double getWeight() {
        return weight;
    }

    public void setWeight(double weight) {
        this.weight = weight;
    }

    public InsertDrawable getI() {
        return i;
    }

    public void setI(InsertDrawable i) {
        this.i = i;
    }

    public Computer() {
    }

    public Computer(String brand, double weight, InsertDrawable i) {
        this.brand = brand;
        this.weight = weight;
        this.i = i;
    }
    public void printInfo(){
        i.plug();
    }
}
//可拔插的接口
interface InsertDrawable{
    void plug();
}
//鼠标类
class Mouse implements  InsertDrawable{
    public void plug(){
        System.out.println("拔插鼠标!");
    }
}
//键盘类
class Keyboard implements InsertDrawable{
    public void plug(){
        System.out.println("拔插键盘!");
    }
}
//显示器类
class Monitor implements InsertDrawable{
    public void plug(){
        System.out.println("拔插显示器!");
    }
}
//打印机类
class Printer implements InsertDrawable{
    public void plug(){
        System.out.println("拔插打印机!");
    }
}