0

How do I create an array of different types? If each class is an extension of the _object class, can I just make an _object array and add the extensions to it?

Example:

class _object {
    int type = 1;
    public _object() {
        type = 2;
    }

    public doSomething() {
    }
}

class tree extends _object {
    public tree() {
    }
}

class apple extends _object {
    public apple() {
    }
}

public tree aTree = new tree();
public apple anApple = new apple();

public _object[] objects = new _object[] { aTree, anApple };
3
  • Did you try it? One line can give you an answer... Commented Jul 29, 2012 at 0:55
  • Actually I just came up with the last part of the question while I was asking it. Commented Jul 29, 2012 at 1:15
  • I rewrote this question like 5 times trying to simplify it. I'm trying to make a grid class that objects can register themselves to. Then objects can request a list of other objects within its grid square. Commented Jul 29, 2012 at 1:19

2 Answers 2

2

The example in your question works. This is known as polymorphism.

http://docs.oracle.com/javase/tutorial/java/IandI/polymorphism.html

http://en.wikipedia.org/wiki/Polymorphism_in_object-oriented_programming

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

Comments

0

After setting up the above code in android as a project and debugging it, it in fact does work, so long as you only call methods of the base object.

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.