Demonstrate getting the immediate superclass information in Java


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

A program that demonstrates this is given as follows −

Example

 Live Demo

package Test;
import java.lang.*;
class Class1{ }
class Class2 extends Class1{ }
public class Demo {
   public static void main(String args[]) {
      Class1 obj1 = new Class1();
      Class2 obj2 = new Class2();
      Class c;
      c = obj2.getClass();
      System.out.println("The class of object obj2 is: " + c.getName());
      c = c.getSuperclass();
      System.out.println("The super class of object obj2 = " + c.getName());
   }
}

Output

The class of object obj2 is: Test.Class2
The super class of object obj2 = Test.Class1

Now let us understand the above program.

First the classes class1 and class2 are defined. A code snippet which demonstrates this is as follows −

class Class1{ }
class Class2 extends Class1{ }

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

Class1 obj1 = new Class1();
Class2 obj2 = new Class2();
Class c;
c = obj2.getClass();
System.out.println("The class type of object obj2 is: " + c.getName());
c = c.getSuperclass();
System.out.println("The super class of object obj2 = " + c.getName());

Updated on: 30-Jul-2019

95 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements