Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Recognizing extended class object

Tags:

java

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.

like image 332
MacHans Avatar asked Dec 14 '12 18:12

MacHans


1 Answers

if (x instanceof Num_int) {
  System.out.println("int");
} else {
  System.out.println("other");
}
like image 112
Louis Wasserman Avatar answered Sep 24 '22 15:09

Louis Wasserman