Search code examples
javainstancepoint

Confusion on creating new instances in java


I am not sure why this line of code does not work in java:

    Point point1 = (1,2);

Instead it should be like this:

    Point point1 = new Point(1,2);

Solution

  • Whenever you want to instantiate an object in Java, excepting primitive types (long, int, bool, etc), you will need to use the new operator.

    (1,2) is not a valid Java object literal and as such cannot be instantiated to a type of Point.

    Instead, you will need to instantiate the object with new and call the (int, int) constructor.

    That looks like your second example

    Point point = new Point(1, 2);
    

    The only time you can instantiate without new is when using a valid literal (or array initializer) that can be instantiated

    All completely valid:

    String x = "NewString";
    int y = 5;
    double z = 3.14;
    int[] x = {1,2,3}; //creates an array in one swoop!
    

    Not sure what your question was, but I hope this clears it up.