2 Replies - 470 Views - Last Post: 19 October 2013 - 01:10 AM Rate Topic: -----

#1 majician  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 1
  • Joined: 18-October 13

creating array of objects from 2 classes

Posted 18 October 2013 - 08:12 PM

to put simply:

i have a baseclass and subclass
i create objects of both in a main method

In a third class I've created an array of the baseclass type (where I would like to store said objects)

I'm lost in this though. Do I create the array strictly in the main method, instead? If not, how do I tell a 3rd class method I want to store objects from 2 other classes into it... without using the main method?

I want to figure it out but I need to be guided, that's why I didn't post the code. Guide me. :)

Is This A Good Question/Topic? 0
  • +

Replies To: creating array of objects from 2 classes

#2 The Arcanist  Icon User is offline

  • New D.I.C Head

Reputation: 5
  • View blog
  • Posts: 37
  • Joined: 27-August 13

Re: creating array of objects from 2 classes

Posted 18 October 2013 - 09:36 PM

It depends on how you want to use the array. I assume you would be using the array in the main method, in which case it will be better if you created it in the main method.
You could use the 3rd class to accomplish the task as well. I don't exactly get what problem you are facing while creating objects from two different classes there. It will be pretty similar to what would do in the main method.

Cheers
Was This Post Helpful? 0
  • +
  • -

#3 Flukeshot  Icon User is offline

  • A little too OCD
  • member icon

Reputation: 417
  • View blog
  • Posts: 1,030
  • Joined: 14-November 12

Re: creating array of objects from 2 classes

Posted 19 October 2013 - 01:10 AM

Put as little code as possible into your main method. It's a static method and you want to keep your program out of a static context.

It may be possible, depending on your needs, to create the items for your array in the array class itself.

class BaseClass {
   private String classDescription = "This is the Base class";

   public String getDescription() {
      return classDescription;
   }
}

class BaseArrayClass {
   private BaseClass[] baseArray = new BaseClass[5];
   for(int i = 0; i < baseArray.length; i++) {
      baseArray[i] = new BaseClass();
   }
}

public class MainClass {
   public static void main(String[] args) {
      new BaseArrayClass();
   }
}


As you can see, the main method is short and sweet and the array class handles the initiation of the base objects it needs to populate its array. Try something like that and come back if you need any further help. Don't be afraid to post code though, we won't do your homework for you.
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1