Determine the Superclass of an Object


To find the superclass of an object we first need to call the getClass() method of the object to return the Class-object.
The Class object then has a method called getSuperClass() which returns another Class object on which the method getName() can be called.
In the example below we call the getSuperClass() method for four different object types: Vector, ArrayList, String and Integer.



import java.util.ArrayList;
import java.util.Vector;
/**
 * Main.java
 *
 * @author www.javadb.com
 */

public class Main {
    
    /**
     * Constructor
     */

    public Main() {
        
        checkObjectSuperClass(new Vector());
        checkObjectSuperClass(new ArrayList());
        
        checkObjectSuperClass("Test String");
        checkObjectSuperClass(new Integer(1));
        
    }
    
    /**
     * Checks which superclass the object has.
     *
     * @param testObject The object
     */

    public void checkObjectSuperClass(Object testObject) {
        
        System.out.println("Object has the superclass " + testObject.getClass().getSuperclass().getName());
        
    }
    
    /**
     * Starts the program
     *
     * @param args the command line arguments
     */

    public static void main(String[] args) {
        new Main();
    }
}


The superclass of Vector and ArrayList classes is the java.util.AbstractList class, the String class is derived from the java.lang.Object class and the Integer class is derived from the java.lang.Number class.
The output from the above code looks like this:


Object has the superclass java.util.AbstractList
Object has the superclass java.util.AbstractList
Object has the superclass java.lang.Object
Object has the superclass java.lang.Number

Do you know your Java?
Take a Ten-Question-Java-Quiz!

Bookmark and Share




Need help with your Java code? It's secure and confidential.
This is how it works:
Send a detailed description of what you need help with, the more details the better. Also provide a deadline for when it has to be finished. More time means better chance of putting your request into the schedule.

If the request is serious you will shortly receive an email with the price, to which you have to respond if you accept.

Once you have accepted, the work will begin on developing your code by an experienced Java developer. When the code is finished a link to a secure payment will be sent to you.

The source code is then sent to you once the payment is completed.

IMPORTANT! The request needs to be very detailed, else it may be ignored.


Write your detailed request here:

E-mail address: