Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Passing Array of objects to a different class

 
K Regan
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 904
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

How about making an accessor method ?


/Svend Rost
 
marc weber
Sheriff
Posts: 11343
Java Mac Safari
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Pass the array of objects from the first class to the constructor of the second class?

 
Amit Saini
Ranch Hand
Posts: 280
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 904
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
@ 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
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic