| Author |
Passing Array of objects to a different class
|
K Regan
Greenhorn
Joined: Oct 20, 2004
Posts: 1
|
|
Any ideas how I can use an array of objects that I have created in one class, in another class? Sounds really simple but is giving me major problems.
|
 |
Svend Rost
Ranch Hand
Joined: Oct 23, 2002
Posts: 904
|
|
Hi, How about making an accessor method ? /Svend Rost
|
 |
marc weber
Sheriff
Joined: Aug 31, 2004
Posts: 11343
|
|
Pass the array of objects from the first class to the constructor of the second class?
|
"We're kind of on the level of crossword puzzle writers... And no one ever goes to them and gives them an award." ~Joe Strummer
sscce.org
|
 |
Amit Saini
Ranch Hand
Joined: Oct 20, 2004
Posts: 280
|
|
You can just use an instance of the class to access its array. Consider this. class1.java ------------ public class class1 { public String firstName; public String lastName; class1(){}; class1(String firstName, String lastName) { this.firstName = firstName; this.lastName = lastName; } } class2.java (Create an array c1array of class1 objects) -------------- public class class2 { public class1 c1 = new class1("Amit", "Saini"); public class1 c2 = new class1("Rohit", "Saini"); public class1 c1array[] = {c1,c2}; //array of class1's objects } class3.java (Use the array created in class2) ------------- public class class3 { public static void main(String args[]) { class2 c2 = new class2(); for (int i=0; i<c2.c1array.length; ++i) { System.out.println(c2.c1array[i].firstName + " " + c2.c1array[i].lastName); } } } OUTPUT ---------- C:\eclipse\workspace\helloworld>java class3 Amit Saini Rohit Saini Hope this helps! Amit
|
 |
Svend Rost
Ranch Hand
Joined: Oct 23, 2002
Posts: 904
|
|
@ amitdsaini: Even though your approach works, one should try to obey the Law of Demeter aka. Don't talk to strangers http://www.ccs.neu.edu/home/lieber/LoD.html /Svend Rost
|
 |
 |
|
|
subject: Passing Array of objects to a different class
|
|
|