If class B
and class C
extend class A
and I have an object of type B
or C
, how can I determine of which type it is an instance?
getClass() If an instance of an object is available, then the simplest way to get its Class is to invoke Object. getClass() .
In computer programming, the object class refers to a class created to group various objects which are instances of that class. Classes are code templates for creating objects. In cases where objects need to be grouped in a certain way, an object class is the "container" for a set of objects built on these templates.
The GetType method is inherited by all types that derive from Object. This means that, in addition to using your own language's comparison keyword, you can use the GetType method to determine the type of a particular object, as the following example shows.
In this example, we will learn to determine the class of an object in Java using the getClass () method, instanceof operator, and the isInstance () method. To understand this example, you should have the knowledge of the following Java programming topics:
Here, we have used the isInstance () method of the class Class to check if the object obj is an object of the class Test. The isInstance () method works similarly to the instanceof operator.
An object is an instance of a class. When a class is created, no memory is allocated. Objects are allocated memory space whenever they are created. The class has to be declared only once. An object is created many times as per requirement. available in the memory.
This method will return true if our object sent as the method's argument passes the IS-A test for the class or interface type. We can use the isInstance () method to check the class of an object at runtime.
if (obj instanceof C) { //your code }
Use Object.getClass(). It returns the runtime type of the object.
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