1

If I create an Array in the class DefaultItems:

DefaultItems[] items = new DefaultItems[20];

I want to use this as a storage array for 5 different class objects. I want to store a Car object, Person object and Pet object.

 DefaultItems[1] = Car Object;
 DefaultItems[2] = Person Object;

Is this possible?

2
  • Are they subclasses of DefaultItms? Commented Oct 27, 2012 at 1:12
  • 2
    Sounds like a terrible design. Why would a Car, Person, and Pet object be encapsulated into an array? This is a miscarriage of object-oriented design. Commented Oct 27, 2012 at 1:23

3 Answers 3

1

If Car and Person derive from DefaultItems then your code should work (assuming the typos are fixed).

If the classes are not related in any way then you can achieve what you want by using Object[] instead of DefaultItems[]. All classes derive from Object.

Sign up to request clarification or add additional context in comments.

Comments

0

It is possible, in a type safe way, just if all the obejcts you want to store in the array share a common parent class from which they inherit:

class Car extends MyObject {
  ...
}

class Person extends MyObject {
  ...
}

MyObject[] array = new MyObject[2];
array[0] = new Car();
array[1] = new Person();

But after having added them to the array they can be accessed just as MyObject instances (unless you typecast them, which must be avoided), so if MyObject class doesn't provide a common interface then this is pretty pointless. It's better to use composition:

class MyClass {
  Person person;
  Car car;
  ..
}

Comments

0

Make sure all your 5 objects i.e. Car, Person etc. are extended from base class DefaultItems. Once you do that, you can achieve what you want.

i.e.

 public class Person extends DefaultItems {
   //...
 }

 public class Car extends DefaultItems {
   //...
 }

then

 DefaultItems[] items = new DefaultItems[2];
 DefaultItems[0] = new Person();
 DefaultItems[1] = new Car();

One example with Number class and its sub classes as is as below:

    Number[] nums = new Number[3];
    nums[0] = new Integer(0);
    nums[1] = new Double(1.0);
    nums[2] = new Float(0.5);

    for(Number num: nums){
        System.out.println(num);//<--prints the numbers
    }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.