错误消息非静态变量无法从静态上下文中引用
第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/