Results 1 to 5 of 5
  1. #1
    ShitalJain is offline Member
    Join Date
    Jun 2011
    Posts
    10
    Rep Power
    0

    Default Function call returning array of objects

    Hi all,
    I want to know how to call a function having same return type as that of class which returns array of objects. Problem i'm facing is how to call the function and catch the array.
    Here is the code i'm trying to execute:
    public class A{

    private int x;
    private int y;

    public A(int j, int k)
    {
    x=j;
    y=k;
    }
    public A create()
    {
    A[] obj= new A[5];
    for(int n=0;n<5;n++)
    {
    obj[n]=new A(n,n+1);
    }
    return obj;
    }

    public static void main(String args[])
    {
    A[] ob = new A[5];
    ob= create();
    System.out.println(ob[0].x+" "+ob[0].y);
    }
    }


    Regards,
    ShitalJain.

  2. #2
    mine0926 is offline Senior Member
    Join Date
    Apr 2010
    Location
    Philippines
    Posts
    580
    Rep Power
    5

    Default

    Not sure what "A" is but

    Change
    Java Code:
    public A create()
    TO
    Java Code:
    public A[] create()

  3. #3
    DarrylBurke's Avatar
    DarrylBurke is offline Member
    Join Date
    Sep 2008
    Location
    Madgaon, Goa, India
    Posts
    11,202
    Rep Power
    19

    Default

    And Java has methods, not functions.

    db

  4. #4
    Junky's Avatar
    Junky is offline Grand Poobah
    Join Date
    Jan 2011
    Location
    Dystopia
    Posts
    3,789
    Rep Power
    7

    Default

    Java Code:
    A[] ob = new A[5];
    ob= create();
    Why waste resources creating an array on line 1 when you immediately throw it away on line 2? Also since create is an uinstance method you cannot access it from main without an instance of the A class. Therefore your code should be:
    Java Code:
    A a = new A();
    A[] ob = a.create();
    // or
    A[] ob = new A().create();

  5. #5
    ShitalJain is offline Member
    Join Date
    Jun 2011
    Posts
    10
    Rep Power
    0

Similar Threads

  1. Call a function via URL
    By cali_guy_0024 in forum New To Java
    Replies: 7
    Last Post: 04-10-2011, 05:04 AM
  2. Polygons... returning and passing objects?
    By asherwolf in forum New To Java
    Replies: 3
    Last Post: 07-09-2010, 04:41 PM
  3. function call error
    By peter_thm in forum New To Java
    Replies: 2
    Last Post: 01-13-2010, 12:57 PM
  4. Rewrite as a function so it can call from main.
    By thangli in forum New To Java
    Replies: 2
    Last Post: 11-30-2008, 06:26 AM
  5. help with System.exit (1) function call
    By katie in forum Advanced Java
    Replies: 2
    Last Post: 08-06-2007, 08:03 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •