-
Passing Array Objects
Working on a school project, and I'm trying to do something like this . I'm still stuck though, I can't get it. Here's what I'm trying to do if it's not clear:
PHP Code:
class blah
{
array a[] = {1, 7, 3, 9, 10, 29}
}
class bloo
{
//Access array 'a' here, with the same values?
}
Thanks
*EDIT* Whoops, should have put this in the "New to Java" forum.
-
threre are 2 ways i can think of at the moment,
1. when you create a new instance of the class bloo, pass it the array and in the constructor of the class bloo allow for an array to be passed as a parameter
2. make the array pubic and static ie:
public static array a[] = {1, 7, 3, 9, 10, 29};
then in the other class you can access it by typing:
blah.a[];
A kram a day keeps the doctor......guessing
-
re:
I think the first option would work for me best. However, I'm not completely sure on what you said. Do you happen to have a documentation of this method or something somewhere?
Thanks!
-
no sorry i dont have any direct documentation, but ill give it a go! 
when you create a new instance of the class bloo you would write somethin glike this:
Code:
bloo myBloo = new bloo();
this will call the constructor method of the class bloo.
so what i suggest you do is to do this instead:
Code:
bloo myBloo = new bloo(a[]);
now, remember that you also have to allow for this in the bloo class, so within the bloo class you must make sure that the constructor has a parameter which is of an array type:
Code:
class bloo
{
int[] array;
bloo(int[] ar){
array = ar;
}
}
or something along those lines, the only thing im not sure of is the syntax for passing arrays in methods, so you may want to check up on that.
A kram a day keeps the doctor......guessing
-
This should work correctly Kram.
Personally I prefer the getter/setter aproach though, since this is much more in line with OOP.
[code]
class blah
{
private array a[] = {1, 7, 3, 9, 10, 29};
public void setA(int[] a)
{
this.a=a;
}
public int[] getA()
{
return a;
}
}
class bloo
{
public static void main(String[] args)
{
blah b = new blah();
int[] a = b.getA();
for (int i=0; i<a.length; i++)
{
System.out.println("value " + i + "=" + a[i]);
}
}
}
-
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
Forum Rules
|
Top DevX Stories
Easy Web Services with SQL Server 2005 HTTP Endpoints
JavaOne 2005: Java Platform Roadmap Focuses on Ease of Development, Sun Focuses on the "Free" in F.O.S.S.
Wed Yourself to UML with the Power of Associations
Microsoft to Add AJAX Capabilities to ASP.NET
IBM's Cloudscape Versus MySQL
|
Bookmarks