有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

使用静态导入时的java未定义方法

我正在阅读《Java思考,第四版》,但无法通过此练习:

Create two packages: debug and debugoff, containing an identical class with a debug( ) method. The first version displays its String argument to the console, the second does nothing. Use a static import line to import the class into a test program, and demonstrate the conditional compilation effect.

很明显,我遗漏了一些东西,因为当我尝试这个:

// C:\Users\user\Documents\EclipseProjects\DebugOnOff\bin\debugonoff\debugon
package debugonoff.debugon;
public class Test {
    public static void debug(String str) {}
}

// C:\Users\user\Documents\EclipseProjects\DebugOnOff\bin\debugonoff\debug
package debugonoff.debug;
public class Test {
    public static void debug(String str) {
        System.out.println(str);
    }
}

// C:\Users\user\Documents\EclipseProjects\DebugOnOff\bin
import static debugonoff.debug.Test.*;
public class TestProgram {
    public static void main(String[] args) {
        debug("Hi there!");
    }
}

出现以下错误消息:

The method debug(String) is undefined for the type TestProgram

这里有什么问题


共 (3) 个答案

  1. # 1 楼答案

    这段代码应该有效。至少对我来说是这样

    您使用哪种编译器、Java版本、IDE和操作系统

    请注意,参考oracle documentation的其他两条评论不正确。可以为方法执行静态导入。文档中的示例是

    import static java.lang.Math.*; double r = cos(PI * theta);

  2. # 2 楼答案

    你能检查一下你的项目设置吗

    我把你的代码复制到了我的一个项目中,效果很好

    从您所展示的路径来看,您的代码似乎位于bin目录中,eclipse通常会将编译的.class文件放在该目录中。您的源文件应该位于src目录中

  3. # 3 楼答案

    不能使用指定的静态导入来导入方法

    1. 可以使用静态导入来访问或导入成员(对象)

    例如:系统。出来println(“”)->;可以替换为 出来println(“”);如果您对java进行了静态导入。lang.System.*

    1. 无论如何,不建议过多地使用静态导入,因为它会降低代码的可读性和可维护性

    2. 静态方法只能访问最小的类。methodName() 或者像往常一样使用新类()。methodName()

    如果您不清楚,请添加评论