如何打印界面的方法

时间:2019-04-10 16:04:03

标签: java

如何打印接口的连接方法? 我只想通过最小化类修改来修改电源。

如果我使用arr [0] .connect(); 错误: 对于设备类型,未定义方法connect()

public class main{

    private static Device arr[];

    public static void main(String[] args) {
        // TODO Auto-generated method stub

        init();
        arr[0].print();
        arr[1].print();

    }

    public static void init() {
        arr = new Device[2];
        arr[0] = new Printer();
        arr[1] = new UsbMem();
    }

}

public interface Connectable {
    public static final String name = ":USB";
    public abstract void connect();
}

public abstract class Device {
    public abstract void print();
}

public class Printer extends Device implements Connectable {

    public void print() {
        System.out.println("It's a printer");
    }

    public void connect() {
        System.out.println(name + "connect with printer");
    }
}

public class UsbMem extends Device implements Connectable {

    public void print() {
        System.out.println("USB memory");
    }

    public void connect() {
        System.out.println(name + "connect with usb memory");
    }
}

这是一台打印机。 :USB连接打印机 USB记忆体 :USB连接USB存储器

2 个答案:

答案 0 :(得分:1)

Device需要实现Connectable

public class Main {

    private static Device arr[];

    public static void main(String[] args) {
        // TODO Auto-generated method stub

        init();
        arr[0].print();
        arr[1].print();
    }

    public static void init() {
        arr = new Device[2];
        arr[0] = new Printer();
        arr[1] = new UsbMem();
    }
}

public interface Connectable {
    public static final String name = ":USB";
    public abstract void connect();
}

public abstract class Device implements Connectable {
    public abstract void print();
}

public class Printer extends Device {

    public void print() {
        System.out.println("It's a printer");
    }

    public void connect() {
        System.out.println(name + "connect with printer");
    }
}

public class UsbMem extends Device {

    public void print() {
        System.out.println("USB memory");
    }

    public void connect() {
        System.out.println(name + "connect with usb memory");
    }
}

答案 1 :(得分:0)

将对象投射到可连接对象

((Connectable)arr[0]).connect()