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 then getSuperClass() 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.

Byron Kiourtzoglou

Byron is a master software engineer working in the IT and Telecom domains. He is an applications developer in a wide variety of applications/services. He is currently acting as the team leader and technical architect for a proprietary service creation and integration platform for both the IT and Telecom industries in addition to a in-house big data real-time analytics solution. He is always fascinated by SOA, middleware services and mobile development. Byron is co-founder and Executive Editor at Java Code Geeks.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button