2

I am a beginner in java. I want to create array of inner class in class other than outer class. But I can't as compiler shows error '(' expected. Help.

Tree test = new Tree();
Tree.Node[] A = test.new Node[10];

error

Tree.java:72: error: '(' expected
Tree.Node[] A = test.new Node[10];
                         ^
1 error
K.M.B
  • 31
  • 6

2 Answers2

1

When you create an array you don't create instances of the element type, you just create an array containing null references, so you create it as you would any array (regardless of the element type being an inner class):

Tree.Node[] A = new Tree.Node[10];

When you initialize an element of the array, you create an instance of the inner class, which requires an enclosing class instance:

A[0] = test.new Node ();
Eran
  • 387,369
  • 54
  • 702
  • 768
0

This code-line:

Tree.Node[] A = test.new Node[10];

is invalid, you are maybe confused with the syntax for creating an instance only

Tree.Node fooA = test.new Node();

what you are looking to do must be written as:

Tree.Node[] A = new Tree.Node[10];

that is the correct way to declare an array of inner classes in java

ΦXocę 웃 Пepeúpa ツ
  • 47,427
  • 17
  • 69
  • 97