Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using instanceof operator in Java

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.

like image 508
One Two Three Avatar asked Aug 01 '26 02:08

One Two Three


1 Answers

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).

like image 165
JB Nizet Avatar answered Aug 02 '26 15:08

JB Nizet