gpt4 book ai didi

java - 从两个具有实现的不同类调用方法

转载 作者:行者123 更新时间:2023-11-29 03:27:08 25 4
gpt4 key购买 nike

好的,所以我必须创建一个 consoleprint 接口(interface)类和另外两个实现它的类

一个类只是让我打印文本,另一个你可以看到的是字符串拆分器。到目前为止,我的测试仪有问题

public interface ConsolePrint {

public void printInfo(String infoToPrint);

}

public class SimplePrint implements ConsolePrint {

public void printInfo (String infoToPrint) {
printInfo("Heading this is not fancy");
}
}

public class FancyPrint implements ConsolePrint {

public void printInfo (String printInfo) {
for (String splitter: printInfo.split("", 1)){
System.out.println(splitter);
}
}
}

这是我遇到问题的测试人员

import java.util.*;

public class ConsolePrintTest {

public static void main(String[] args) {
}

SimplePrint mySp = new SimplePrint();
FancyPrint myFp = new FancyPrint();

myFp.printInfo(); <-----error appearing here

}

任何帮助都会非常感谢

最佳答案

您需要将您的方法调用移动到您的main 方法(或至少一些 方法)。目前它不在方法中 - 只有声明(字段、方法、嵌套类型等)可以位于类的顶层。

此外,您当前没有将参数传递给 printInfo 方法,但是

这样就好了:

public class ConsolePrintTest {
public static void main(String[] args) {
FancyPrint myFp = new FancyPrint();

myFp.printInfo("some string");
}
}

注意:

  • 我已经删除了类中的导入,因为它不相关
  • 我删除了 mySp 声明,因为该变量从未被使用过
  • 您目前没有使用类实现接口(interface)这一事实。您可能需要考虑:

    ConsolePrint printer = new FancyPrint();
    printer.printInfo("some string");

如评论中所述,您的 SimplePrint 实现也无条件递归,因此这是要解决的嵌套问题。

关于java - 从两个具有实现的不同类调用方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20453671/

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