In Java, I have a class Num
, and a few classes that extend Num
, like Num_int
and Num_double
.
I want to know whether it's possible for a method to recognize whether a given Num
object is a Num_int
or not.
I have the following code:
void test(Num_int x) {
System.out.println("int");
} // test
void test(Num x) {
System.out.println("other");
} // test
Num_int A = new Num_int( );
Num B = new Num_int( );
Num C = new Num_double( );
test(A); // prints "int"
test(B); // prints "other"
test(C); // prints "other"
Unfortunately, the method "test" only prints "int" when A is given as argument.
I wan't the function to also print "int" when B is passed, since B is created via Num B = new Num_int( );
. Is this possible?
Thanks.
if (x instanceof Num_int) {
System.out.println("int");
} else {
System.out.println("other");
}
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