java - 不能从静态内容中引用非静态方法

标签 java

我无法编译以下代码:

public class Test {
 public static void main (String [] args ){
  int a = calcArea(7, 12);
  System.out.println(a);
 }

 int calcArea(int height, int width) {
  return height * width;
 }
}

出现如下错误:

Non-static method calcArea(int, int) cannot be referenced from static content

这是什么意思?我该如何解决这个问题……?

编辑:

根据您的建议,我创建了一个新的 test() 实例,如下所示:

public class Test {
    int num;
    public static void main (String [] args ){
        Test a = new Test();
        a.num = a.calcArea(7, 12);
        System.out.println(a.num);
    }

    int calcArea(int height, int width) {
            return height * width;
    }

}

这是正确的吗?如果我这样做有什么区别...

public class Test {
 public static void main (String [] args ){
  int a = calcArea(7, 12);
  System.out.println(a);
 }

 static int calcArea(int height, int width) {
  return height * width;
 }
}

最佳答案

您的 main 是静态的,因此您可以在没有类测试实例的情况下调用它 (new test())。但它调用的 calcArea 不是静态的:它需要类的实例

我猜你可以这样重写它:

public class Test {
 public static void main (String [] args ){
  int a = calcArea(7, 12);
  System.out.println(a);
 }

 static int calcArea(int height, int width) {
  return height * width;
 }
}

正如评论和其他答案所暗示的那样,您可能不想走这条路:您将只获得静态函数。弄清楚你的代码中静态实际上应该是什么,也许让你自己成为一个对象并从那里调用函数:D

关于java - 不能从静态内容中引用非静态方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4774376/

相关文章:

java - Netbeans 8.0 不能与 LibGDX 一起使用?

java - 如何检查参数是否存在于数组列表中

java - Spring Boot 和 Docker-compose 设置参数

java - 如何从服务器返回 UIMA Ruta 的输出?

java - 从 Apache HttpClient 中的 HttpResponse 对象获取 JSON 属性

java - 保证多边形法线的向外方向

java - 使用 protected 变量比使用 getter 和 setter 有什么优势吗?

java - 如何在 Spring 的单个事务中使用多个数据源(一个用于读取,另一个用于写入)?

java - 在android中使用公历获取当前的儒略日数

使用 SQL 的 Java Swing 计时器