Suppose I am modelling different animals in Java. Every animal has some combination of these abilities: walk, swim and fly. For the example, the ability set is constant.
I can store this information as getters that return constants. For example:
public class Penguin implements Animal {
public boolean canWalk() {
return true;
}
public boolean canSwim() {
return true;
}
public boolean canFly() {
return false;
}
// implementation...
}
The run-time check is then:
if (animal.canFly()) {
// Fly!
}
Or I can use "tagging" interfaces:
public class Penguin implements Animal, Flyer, Swimmer {
// implementation...
}
The run-time check is then:
if (animal instanceof Flyer) {
// Fly!
}
What are the advantages and disadvantages of each approach?
Marker interfaces are a bit of an anti-pattern in modern Java, required in earlier times because of no way to directly add metadata to a class. The "modern" approach is annotations:
@Retention(RetentionPolicy.RUNTIME)
@interface Flyer {
}
@Retention(RetentionPolicy.RUNTIME)
@interface Swimmer {
}
@Flyer @Swimmer
public class Penguin implements Animal {
}
And the runtime check:
if(Animal.class.isAnnotationPresent(Flyer.class)) {
// fly!
}
You can use this approach if all you want to know is if an Animal
has this trait, that is flight and swimming capability is pure metadata.
What are you trying to achieve? I wouldn't call this OOP, because the OOP approach is usually not to query capabilities and execute object-specific conditional logic, it is to use polymorphism.
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