Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

object is an instance of 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 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.

like image 320
user1608045 Avatar asked Aug 17 '12 23:08

user1608045


People also ask

Is object an instance of class?

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.

Is instance same as object in Java?

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.

Is object instance and class are same?

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.


2 Answers

if (object instanceof RoomBooking) ...

And an interesting read

like image 92
assylias Avatar answered Sep 21 '22 16:09

assylias


There is also the isAssignableFrommethod 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)
like image 30
ssedano Avatar answered Sep 20 '22 16:09

ssedano