Home > database >  Java problem "Cannot instantiate the type Point2D"
Java problem "Cannot instantiate the type Point2D"

Time:01-22

I'm trying to use the Point2D class in java and I simple cannot create an object.

import java.awt.geom.Point2D; import java.util.Scanner;

public class TestPoint2D {

    public static void main(String[] args) {

        Scanner input = new Scanner(System.in);

        System.out.println("Enter point1's x-, y-coordinates: ");
        double x1 = input.nextDouble();
        double y1 = input.nextDouble();
        System.out.println("Enter point2's x-, y-coordinates: ");
        double x2 = input.nextDouble();
        double y2 = input.nextDouble();

        Point2D p1 = new Point2D(x1,y1);
        System.out.println("p1 is ")  p1.toString();
        
    }

}

CodePudding user response:

That is not how you instantiate a Point2D instance. I believe you want the Point2D.Double(double, double) constructor. Also, you have a typo in your print. It should be something like

Point2D p1 = new Point2D.Double(x1, y1);
System.out.println("p1 is "   p1);

CodePudding user response:

Point2D is an abstract class present in the package java.awt.geom.Point2D. For abstract classes, you cannot form a object [why ? ] You have to check your import statements that it is not importing the class from the above package and is trying to create the objects of class that you have defined .

Apart from this , there is compilation error in your println statement as it is missing a ) bracket. This code does not show any compilation error.

import java.util.Scanner;
// import java.awt.geom.Point2d // comment this out if it is present in import. 
public class Main {
    public static void main(String[] args) {

        Scanner input = new Scanner(System.in);

        System.out.println("Enter point1's x-, y-coordinates: ");
        double x1 = input.nextDouble();
        double y1 = input.nextDouble();
        System.out.println("Enter point2's x-, y-coordinates: ");
        double x2 = input.nextDouble();
        double y2 = input.nextDouble();

        Point2D p1 = new Point2D(x1,y1);
        System.out.println("p1 is "  p1.toString()); // compilator error : missing ) ; 
        
    }
}
class Point2D
{
    double x, y;

    public Point2D(double x, double y) {
        super();
        this.x = x;
        this.y = y;
    } 
    
}
  •  Tags:  
  • Related