0

Error message non-static variable this cannot be referenced from a static context line 18 (the print out line in the main method. Why am I getting this error message and how do I fix it?

 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)));

     }       
   }
}
sam
  • 2,033
  • 2
  • 10
  • 13
Allie Carroll
  • 9
  • 1
  • 1
  • 3
  • Check [`“Non-static method cannot be referenced from a static context” error`](http://stackoverflow.com/questions/4922145/non-static-method-cannot-be-referenced-from-a-static-context-error) – sam Oct 29 '15 at 19:08
  • This answer will help you - [http://stackoverflow.com/questions/2559527/non-static-variable-cannot-be-referenced-from-a-static-context](http://stackoverflow.com/questions/2559527/non-static-variable-cannot-be-referenced-from-a-static-context) – mrcrag Oct 29 '15 at 19:47

1 Answers1

1

you are instantiating a nested non static class inside a static method. if a nested class is not static, that means that every instance of the enclosing class has its own nested class, therefor in order to instatntiate the nested class, you will need an instance of the enclosing class first.

simplest solution is to make the nested class static:

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)));

  }       
}
}