class
Get the super-class of an object
In this example we shall show you how to get the superclass of an Object. We can try to get the superclass of any Java class, as shown in the steps below:
- We create an Object and a new Class object.
- We create a new String object.
- We set to the Class object the String object’s superclass, using
getClass()
API method of Object for the object to get its class, and thengetSuperClass()
API method of Class. - Then we create a new Object instance and follow the above steps to get its superclass that is
null
. - We follow the same steps creating a new HashMap object.
-
We follow the same steps, creating a new Observer object that overrides the
update(Observable o, Object arg)
method of Observer interface,
as described in the code snippet below.
package com.javacodegeeks.snippets.core; import java.util.HashMap; import java.util.Observable; import java.util.Observer; public class GetTheSuperClassOfAnObject { public static void main(String[] args) { Object object; Class<?> superClass; // Superclass of String is Object object = new String(); superClass = object.getClass().getSuperclass(); System.out.println("String superClass: " + superClass); // Superclass of Object is null object = new Object(); superClass = object.getClass().getSuperclass(); System.out.println("Object superClass: " + superClass); object = new HashMap<Object, Object>(); superClass = object.getClass().getSuperclass(); System.out.println("HashMap superClass: " + superClass); object = new Observer() { @Override public void update(Observable o, Object arg) { } }; superClass = object.getClass().getSuperclass(); System.out.println("Observer superClass: " + superClass); } }
Output:
String superClass: class java.lang.Object
Object superClass: null
HashMap superClass: class java.util.AbstractMap
Observer superClass: class java.lang.Object
This was an example of how to get the superclass of an Object in Java.