Get super class of an object in Java

Java 8Object Oriented ProgrammingProgramming

The immediate superclass of any entity such as an object, class, primitive type, interface etc. can be obtained using the method java.lang.Class.getSuperclass(). This method contains no parameters.

A program that demonstrates this is given as follows −

Example

 Live Demo

public class Main {
   public static void main(String[] args) {
      Object obj1 = new String("Hello");
      Object obj2 = new Integer(15);
      Class c1 = obj1.getClass().getSuperclass();
      System.out.println("Super Class = " + c1);
      Class c2 = obj2.getClass().getSuperclass();
      System.out.println("Super Class = " + c2);
   }
}

Output

Super Class = class java.lang.Object
Super Class = class java.lang.Number

Now let us understand the above program.

In the method main(), getClass() is used to obtain the class and getSuperclass() is used to obtain the super class of objects obj1 and obj2. Then the super class is printed. A code snippet which demonstrates this is as follows −

Object obj1 = new String("Hello");
Object obj2 = new Integer(15);
Class c1 = obj1.getClass().getSuperclass();
System.out.println("Super Class = " + c1);
Class c2 = obj2.getClass().getSuperclass();
System.out.println("Super Class = " + c2);
raja
Published on 09-Jan-2019 07:15:30
Advertisements