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



错误消息non-static variable this cannot be referenced from a static context第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)));
  }       
}
}

相关内容

  • 没有找到相关文章

最新更新