-3

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);
munmunbb
  • 297
  • 9
  • 22

1 Answers1

4

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.

CollinD
  • 7,304
  • 2
  • 22
  • 45
  • 2
    I guess she wanna some good explanation. Good Collin and i like ur photo haha – Fiido93 Sep 04 '15 at 04:33
  • 1
    There's one other case where an object can be created without using the `new` operator, and that is with [array initializers](http://docs.oracle.com/javase/specs/jls/se8/html/jls-10.html#jls-10.6). So you can do things like `int ia[][] = { {1, 2}, null };`. That's completely equivalent to `int ia[][] = new int[][] { new int[] {1, 2}, null };` but much nicer to write. – Ted Hopp Sep 04 '15 at 05:23
  • I think that still falls under the category of valid literals. But it's definitely not intuitive from my answer. I'll throw that in, thanks Ted! – CollinD Sep 04 '15 at 05:25
  • Well, it doesn't have to be literals. You can also write `int[] x = { foo(), bar() };` (where `foo()` and `bar()` are methods that return `int` values). – Ted Hopp Sep 04 '15 at 05:26
  • It's definitely moot at this point, but out of curiosity does that still, in fact qualify as a literal? I suppose not since it has nested dynamic values, but the array itself is still somewhat literally defined. I think you're right though, that wouldn't qualify as a literal since it's not literal thru-and-thru. I think that makes array initializers more of a syntactic sugar than anything else. – CollinD Sep 04 '15 at 05:28
  • 1
    That's my point -- it is not a literal but it is a valid array initializer expression (just not a compile-time constant). – Ted Hopp Sep 04 '15 at 05:29
  • @TedHopp - Also, `MyClass.newInstance()` is another way of getting a *new* instance – TheLostMind Sep 04 '15 at 05:57