Inheritance
More skills
Object's type
How to get information about an object's type
- Every object has a getClass method that returns a Class object that corresponds to the object's type.
- You can use the methods of the Class class to obtain information about any object, such as its name.
- You can use the instanceof operator to check if an object is an instance of a particular class.
The Class class
java.lang.Class
Common method
Method | Description |
---|---|
getName() | Returns a String object for the name of this Class object. |
Example 1: Code that displays an object's type
Product p = new Book(); // create a Book object and assign it to a Product variable Class c = p.getClass(); // get the Class object for the product System.out.println("Class name: " + c.getName()); // print the object type The consoleClass name: Book
Example 2: Code that tests an object's type
Product p = new Book(); // create a Book object if (p.getClass().getName().equals("Book")) System.out.println("This is a Book object"); The consoleThis is a Book object
Example 3: An easier way to test an object's type
Product p = new Book(); // create a Book object if (p instanceof Book) System.out.println("This is a Book object"); The consoleThis is a Book object