teynon
teynon

Reputation: 8298

Android - Create an Array of Variable Object Types

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 };

Upvotes: 0

Views: 479

Answers (2)

dsh
dsh

Reputation: 12214

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

Upvotes: 2

teynon
teynon

Reputation: 8298

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.

Upvotes: 0

Related Questions