I have a base class called class Base and two children classes
class A extends Base
and
class B extends Base
I have a method foo in Base.
Rather than putting the implementation of foo in class A and class B, so that I can do
void foo (Object o)
{
// A's implementation
assert o instanceof A;
}
void foo (Object o)
{
// B's implementation
assert o instanceof B;
}
Is there anyway to put foo in Base, and still still be able to check for the runtime class? I've thought of something like this:
void foo (Object o)
{
// Check that o is instanceof a runtime class
assert o instanceof this.getClass(); // ????
}
Thanks.
You can implement your method like this:
public void foo() {
if (this instanceof A) {
// implementation for A
}
else if (this instanceof B) {
// implementation for B
}
}
But the point of polymorphism is to put the A implementation in A, so that this implementation can use A's private fields to implement the method (same for B, or course).
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