To get the super class of an object we can call the object’s getClass()
method. After getting the class type of the object we call the getSuperclass()
method to get the superclass. Let’s see the code snippet below.
package org.kodejava.lang;
public class ObtainingSuperClass {
public static void main(String[] args) {
// Create an instance of String class
Object object1 = new String("Hello");
// Get String class super class
Class<?> clazz1 = object1.getClass().getSuperclass();
System.out.println("Super Class = " + clazz1);
// Create an instance of StringIndexOutOfBoundsException class
Object object2 = new StringIndexOutOfBoundsException("Error message");
// Get StringIndexOutOfBoundsException class super class
Class<?> clazz2 = object2.getClass().getSuperclass();
System.out.println("Super Class = " + clazz2);
}
}
The program above prints the following string:
Super Class = class java.lang.Object
Super Class = class java.lang.IndexOutOfBoundsException
Latest posts by Wayan (see all)
- How do I get number of each day for a certain month in Java? - September 8, 2024
- How do I get operating system process information using ProcessHandle? - July 22, 2024
- How do I sum a BigDecimal property of a list of objects using Java Stream API? - July 22, 2024