|
Do you need help with your Java programming?
Click here for instant help with your Java code. |
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! | |
Search for code examples on this site
