Class Class

Package: java.lang

Every class used by a Java application is represented in memory by an object of type Class. If your program uses Employee objects, for example, there’s also a Class object for the Employee class. This Class object contains information not about specific employees, but about the Employee class itself.

Methods

Method

Description

String getName()

Returns the name of the Class object.

Class getSuperclass()

Returns a Class object representing the parent class of this Class object. (For more information, see Inheritance in Part 2.)

Getting a Class object

Because Class objects are created by the Java runtime, the Class class has no public constructor. You can get a Class object by using the getClass method. The Object class defines this method, so it’s available to every object. (See Object Class.)

For example:

Employee emp = new Employee();

Class c = emp.getClass();

Warning.eps You have to initialize a variable with an object instance before you can call its getClass method because the getClass method returns a Class object that corresponds to the type of object the variable refers to, not the type that the variable is declared as.

Suppose that an HourlyEmployee class extends the Employee class. Then consider these statements:

HourlyEmployee emp = new Employee();

Class c = emp.getClass();

Here, c refers to a Class object for the HourlyEmployee ...

Get Java For Dummies Quick Reference now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.