Download the JDK
Search the Tutorials
Hide the TOC
Trail: The Reflection API
Lesson: Examining Classes
Examining Classes
Retrieving Class Objects
Getting the Class Name
Discovering Class Modifiers
Finding Superclasses
Identifying the Interfaces Implemented by a Class
Examining Interfaces
Identifying Class Fields
Discovering Class Constructors
Obtaining Method Information
Home Page > The Reflection API > Examining Classes
« Previous • Trail • Next »
Finding Superclasses

> Because the Java programming language supports inheritance, an application such as a class browser must be able to identify superclasses. To determine the superclass of a class, you invoke the `getSuperclass` method. This method returns a `Class` object representing the superclass, or returns null if the class has no superclass. To identify all ancestors of a class, call `getSuperclass` iteratively until it returns null.

> The program that follows finds the names of the `Button` class's ancestors by calling `getSuperclass` iteratively.

> >     import java.lang.reflect.*;
> >     import java.awt.*;

> >     class SampleSuper {

> >        public static void main(String[] args) {
> >           Button b = new Button();
> >           printSuperclasses(b);
> >        }

> >        static void printSuperclasses(Object o) {
> >           Class subclass = o.getClass();
> >           Class superclass = subclass.getSuperclass();
> >           while (superclass != null) {
> >              String className = superclass.getName();
> >              System.out.println(className);
> >              subclass = superclass;
> >              superclass = subclass.getSuperclass();
> >           }
> >        }
> >     }

> The output of the sample program verifies that the parent of `Button` is `Component`, and that the parent of `Component` is `Object`:

> >     java.awt.Component
> >     java.lang.Object

« Previous • Trail • Next »
Previous page: Discovering Class Modifiers
Next page: Identifying the Interfaces Implemented by a Class