You need to do three things to make your code work. I will explain them. Check out the working version first.
public class Array { static String[] a = new String[]{"red", "green", "blue"}; static Point[] p = new Point[]{new Point(1, 2), new Point("3,4")}; public static void main(String[] args) { System.out.println("hello"); } static class Point { int x; int y; Point(int x, int y) { this.x = x; this.y = y; } Point(String s) { String[] a = s.split(","); x = Integer.parseInt(a[0]); y = Integer.parseInt(a[1]); } } }
Listed below are three changes you should make.
1. change "3,4"
to new Point("3,4")
or new Point(3,4)
We know that an array can contain elements of similar types. Here you declare an array named p
type Point
. This means that it can only contain an element of type Point
(or its subtypes). But the second element of "3,4"
is of type String
, and you have a mismatch. Therefore, you must specify either new Point("3,4")
or new Point(3,4)
to get elements of type Point
.
2. You must make your Point
class static
From the Java Tutorial :
An instance of InnerClass can exist only within an instance of OuterClass and has direct access to the methods and fields of its enclosing instance.
Here, your Point
class is an inner class and should have access to all members of the Array
class. To do this, each object of class Point
must be associated with an object of class Array
. But the p
array you create is in a static
context. Thus, you need to either make the class Point
a static
or make the array p
non-stationary.
3. parseInt
not a String
class method
parseInt
is a static method of the Integer
class, not the String
class. Therefore you should name it as Integer.parseInt(stringValue)
.
Hope this helps :)