Object is an instance of a class (java)

System.out.print("Enter Room Number: "); int a4 = scan.nextInt(); scan.nextLine(); booking[count]= new RoomBooking (a1,a2,a3,a4); count++; if (/* if the object is an instance of RoomBooking(subclass) */) { for (int y = 0; y < count; y++) { if (a4 == (((RoomBooking) booking[y]).getRoomNumber())) { System.out.print("Used number, Please Try again"); } } } 

"if the object is an instance of RoomBooking (subclass)" How can I write this in java?

Sorry if that doesn't make sense, I'm still learning.

If you need to know what is going on, there are 2 classes. Booking (regular booking) and RoomBooking (which applies to booking) .. Since we need to create one array that contains a mixture of both, I need to check if the object (a4) is an instance of RoomBooking, so I can compare the numbers.


I tried if ((RoomBooking.class.isInstance (a4))) {...} but this did not work.

+4
source share
2 answers

if (object instanceof RoomBooking) ...

And it’s interesting to read

+18
source

There is also an isAssignableFrom method in Class .

 if(CabinBooking.class.isAssignableFrom(object.getClass()) 

I prefer the method suggested by @assylias , since it would work even in object == null , and isAssignableFrom error if the parameter is null. Therefore, you should verify that the instance is not null.

 if(object instanceof CabinBooking.class) 
+5
source

All Articles