I have an abstract class Entity with several subclasses: SubclassA, SubclassB, and SubclassA has a subclass SubSubClass.
I also have an object someObject of class SomeClass that looks like this:
class SomeClass{
void doSomething(Entity e){..}
void doSomething(SubclassA e){..}
void doSomething(SubclassB e){..}
void doSomething(SubSubClass e){..}
}
I have a List<Entity> list. Every item in this list is passed into someObject.doSomething.
for(Entity entity : list){
someObject.doSomething(entity);
}
Thing is, doSomething(Entity e) is always invoked, no matter what the actual type of the current Entity is, because the reference type is always Entity. To fix this, I need to do casting, like: someObject.doSomething((SubclassB)entity).
So I was wondering if there's a way to cast an object dynamically to whatever concrete type it is, without instanceof operations.
If there is no way to do this, how would you deal with my situation?
Flip it, add a receiveWork (or whatever you want to name it) method (that possibly expects a Runnable or other executable unit) to Entity and its subclasses and invoke that method in your foreach loop. Let polymorphism do the work for you.
If you find yourself tempted to cast an object you have probably already done something wrong.
Your mistake is expecting to write code that does something with an object - instead you should teach the object how to do it itself. This is a central tenet of oop.
See how simple that can be:
class Entity {
public void action(SomeClass c) {
c.doSomething(this);
}
}
class SubclassA extends Entity {
public void action(SomeClass c) {
c.doSomething(this);
}
}
class SubclassB extends Entity {
public void action(SomeClass c) {
c.doSomething(this);
}
}
class SubSubClass extends SubclassA {
public void action(SomeClass c) {
c.doSomething(this);
}
}
class SomeClass {
void doSomething(Entity e) {
System.out.println("Do something (Entity) with an " + e.getClass());
}
void doSomething(SubclassA e) {
System.out.println("Do something (SubclassA) with an " + e.getClass());
}
void doSomething(SubclassB e) {
System.out.println("Do something (SubclassB) with an " + e.getClass());
}
void doSomething(SubSubClass e) {
System.out.println("Do something (SubSubClass) with an " + e.getClass());
}
}
public void test() {
List<Entity> list = new ArrayList<>();
list.add(new Entity());
list.add(new SubclassA());
list.add(new SubclassB());
list.add(new SubSubClass());
SomeClass someObject = new SomeClass();
for (Entity entity : list) {
entity.action(someObject);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With