gpt4 book ai didi

java - 如何打印接口(interface)方法

转载 作者:行者123 更新时间:2023-12-02 10:01:11 26 4
gpt4 key购买 nike

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

如果我使用 arr[0].connect();错误 :Device 类型的 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 存储器

最佳答案

设备需要实现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");
}
}

关于java - 如何打印接口(interface)方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55616910/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com