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 that in java?
Sorry if that doesn't make sense, still learning.
If you need to know what's going on, there are 2 classes. Booking (normal Booking) and RoomBooking ( which extends Booking).. Since we have to create one array which stores a mixture of both, i need to check if the object(a4) is an instance of the RoomBooking so i can compare the numbers.
I have tried if ((RoomBooking.class.isInstance(a4))){...} but it didn't work.
An instance of a class is an object. It is also known as a class object or class instance. As such, instantiation may be referred to as construction. Whenever values vary from one object to another, they are called instance variables.
In Java functions are known as methods, similarly, objects are known as instances in Java. You have a class, which represent a blueprint of a real-world thing e.g. Car, and object represents a real-world car like your car, my car, a red car or a blue car. They are also known as instances of the car.
A class is a blueprint which you use to create objects. An object is an instance of a class - it's a concrete 'thing' that you made using a specific class. So, 'object' and 'instance' are the same thing, but the word 'instance' indicates the relationship of an object to its class.
if (object instanceof RoomBooking) ...
And an interesting read
There is also the isAssignableFrom
method in Class
.
if(CabinBooking.class.isAssignableFrom(object.getClass())
I prefer the method that @assylias
suggested since it would work even in object == null
while isAssignableFrom
would throw an error if the parameter is null. So you must check that the instance is not null.
if(object instanceof CabinBooking.class)
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