I want to create an array of classes outside Main class, but it won\'t compile. If i put ObjectArray code into Main class everything works fine. I tried making a contructor, ext
You cannot have code directly in a class. It needs to be in a method, constructor, or initializer block.
Here, you'd put the code in an initializer block:
class ObjectArray {
Account[] obj = new Account[2];
{
obj[0] = new Account();
obj[1] = new Account();
obj[0].setData(1,2);
obj[1].setData(3,4);
}
...
}
I would however recommend creating a constructor to initialize the object, and then use an array initializer.
You also need to rename the void toString()
method, since it clashes with the String toString()
method inherited from Object
.
In the following code I have also added various spaces to format according to standard style guidelines. Makes the code easier to read.
class Main {
public static void main(String args[]) {
ObjectArray dd = new ObjectArray();
dd.show();
}
}
class ObjectArray {
Account[] obj = { new Account(1, 2), new Account(3, 4) };
public void show() {
obj[0].showData();
obj[1].showData();
}
}
class Account {
private int a, b;
public Account() {
}
public Account(int c, int d) {
a = c;
b = d;
}
public void setData(int c, int d) {
a = c;
b = d;
}
public void showData() {
System.out.println("Value of a = " + a);
System.out.println("Value of b = " + b);
}
}
Output
Value of a = 1
Value of b = 2
Value of a = 3
Value of b = 4
The following code should be inside the constructor:
obj[0] = new Account();
obj[1] = new Account();
obj[0].setData(1,2);
obj[1].setData(3,4);
Also, change the name of toString
in ObjectArray
to something else e.g. showData
. The method name toString
conflicts with the one in its default superclass, Object
.
Complete code:
class ObjectArray {
Account obj[] = new Account[2];
ObjectArray() {
obj[0] = new Account();
obj[1] = new Account();
obj[0].setData(1, 2);
obj[1].setData(3, 4);
}
public void showData() {
obj[0].showData();
obj[1].showData();
}
}
class Account {
int a, b;
public void setData(int c, int d) {
a = c;
b = d;
}
public void showData() {
System.out.println("Value of a =" + a);
System.out.println("Value of b =" + b);
}
}
public class Main {
public static void main(String args[]) {
ObjectArray dd = new ObjectArray();
dd.showData();
}
}
Output:
Value of a =1
Value of b =2
Value of a =3
Value of b =4