Demonstrate getting the immediate superclass information in Java

Java 8Object Oriented ProgrammingProgramming

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());
raja
Published on 09-Jan-2019 10:35:40
Advertisements