java - 错误消息 "non-static variable this cannot be referenced from a static context"第 18 行

标签 java object netbeans

错误消息非静态变量无法从静态上下文中引用第18行(主方法中的打印输出行。为什么我会收到此错误消息以及如何修复它?

 public class MyPoint {

   /**
    * @param args the command line arguments
    */
    public static void main(String[] args) {
      System.out.println(new Point(10D, 10D).distance(new Point(10D,30.5D)));
    }

   class Point
   {
     private final double x;
     private final double y;

     public Point(double x, double y) {
      this.x=0;
      this.y=0;
     }

     public double getX() { return(this.x); }
     public double getY() { return(this.y); }

     public double distance(Point that) {
        return( this.distance(that.getX(), that.getY() ) );
     }

     public double distance(double x2, double y2) {
     return Math.sqrt((Math.pow((this.x - x2), 2) +Math.pow((this.y-        y2),     2)));

     }       
   }
}

最佳答案

您正在静态方法内实例化嵌套的非静态类。 如果嵌套类不是静态的,则意味着封闭类的每个实例都有自己的嵌套类,因此为了实例化嵌套类,您首先需要一个封闭类的实例。

最简单的解决方案是使嵌套类静态:

public class MyPoint {

/**
* @param args the command line arguments
*/
public static void main(String[] args) {
  System.out.println(new Point(10D, 10D).distance(new Point(10D,30.5D)));
}

static class Point
{
 private final double x;
 private final double y;

 public Point(double x, double y) {
  this.x=0;
  this.y=0;
 }

 public double getX() { return(this.x); }
 public double getY() { return(this.y); }

 public double distance(Point that) {
    return( this.distance(that.getX(), that.getY() ) );
 }

 public double distance(double x2, double y2) {
 return Math.sqrt((Math.pow((this.x - x2), 2) +Math.pow((this.y-        y2),     2)));

  }       
}
}

关于java - 错误消息 "non-static variable this cannot be referenced from a static context"第 18 行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33422589/

相关文章:

java - java中带有hashmap实现的电话簿

java - Java在内存中的样子

java - 如何使用 Java 和 apache poi 选择 Excel 中的所有单元格

JavaScript 将对象数组转换为二维数组

c# - 我可以在 Ruby/Java/C# 中创建这样的对象吗?

java - Spring Boot 的 CORS 不在响应 header 中

javascript - 从关联数组启动对象

java - 如何更改菜单栏中子菜单的标签颜色?

php - 具有 xdebug 的 Netbeans 不突出显示调试行

java - 找不到 javax.swing.JOptionPane 的 Netbeans 异常类