Reputation: 365
Let's say I have the following:
public interface Talk {
void Talks();
}
public interface Walk {
void Walks();
}
public class Dog implements Talk, Walk {
public Dog() {
// ...
}
public void Talks() {
// ...
}
public void Walks() {
// ...
}
}
public class Cat implements Talk, Walk {
public Cat() {
// ...
}
public void Talks() {
// ...
}
public void Walks() {
// ...
}
}
I'm trying to add an object from class Dog, Dog dog = new Dog(...), and another object from class Cat, Cat cat = new Cat(...), to the same array, but since they are from different class, they cannot be added in the same array.
So my solution was to create an abstract class, extend Talk and Walk to that abstract class, and have class Dog and Cat inherit from the abstract class, so I can create an array of the abstract class to put dog and cat objects.
Abstract abstract = { new Dog(...), new Cat(...) };
Is there a better solution than this?
Upvotes: 0
Views: 759
Reputation: 88707
Interfaces are already a good start. You could define an array of either Walk
or Talk
but for the combination you'd either need another interface that combines both (and which your classes would need to implement).
You might also want to use collections instead of arrays, e.g. List<Walk>
etc.
Note that I've updated my answer because List<? extends Walk & Talk>
is actually not possible. You could use <T extends Walk & Talk>
and List<T>
but that would only work if you'd use a concrete type for T
, e.g. List<Dog>
. That's useful if you need to make sure that the actual type of the elements implements both interfaces, e.g. if Turtle
would only implement Walk
<T extends Walk & Talk
would not allow Turtle
to be used.
So why isn't List<? extends Walk & Talk>
possible? For one you could not add anything because the compiler would not know whether it would be safe (the wildcard ?
could match a List<Dog>
or List<Cat>
but the compiler doesn't know).
Another reason is: what would be the return type for list.get(index)
? Would it be Walk
? Would it be Talk
? The compiler can't decide and needs you. If you create an interface WalkTalk extends Walk, Talk
you can use that and the compiler is happy :)
Upvotes: 2
Reputation:
Object is the root of all Java Objects. If you declare Object[] or List you can initialize/add any JAVA object to the array or list. And casting when elements are extracted. Example:
Object[] objs = { (Object)(new Dog()), (object)(new Cat(), ... }
// or
List<Object> lobj = new ArrayList<>();
lobj.add((Object) new Dog());
...
Dog dog = (Dog) lobj.get(0);
// or
Cat cat = (Cat)objs[1];
Upvotes: 0