Hi,
I’ve been using inheritance for some of my classes, but I’ve run into some troubles when trying to do the same things with ArrayList
's.
If I have 2 classes class ObjectType1 { }
, class ObjectType2 extends ObjectType1 { }
, and have a function void test(ObjectType1 object) { }
, the function test
can take in ObjectType1
or ObjectType2
. For example:
class ObjectType1 {
ObjectType1() {
}
}
class ObjectType2 extends ObjectType1 {
ObjectType2() {
}
}
ObjectType1 object1 = new ObjectType1();
ObjectType2 object2 = new ObjectType2();
void test(ObjectType1 object) {
}
void draw() {
test(object1);
test(object2);
}
Would work fine, but when I switch everything out to ArrayList
's:
class ObjectType1 {
ObjectType1() {
}
}
class ObjectType2 extends ObjectType1 {
ObjectType2() {
}
}
ArrayList<ObjectType1> object1 = new ArrayList<ObjectType1>();
ArrayList<ObjectType2> object2 = new ArrayList<ObjectType2>();
void test(ArrayList<ObjectType1> object) {
}
void draw() {
test(object1);
test(object2);
}
Would return an error. I could just loop through all of the ArrayList
's elements, but it would be helpful to know if there was a way to have a function be able to take ArrayList<ObjectType1>
and ArrayList<ObjectType2>
.
Any questions or advice are appreciated,
Thanks!