Java Reference
In-Depth Information
Method
Purpose
getSuperclass()
This method returns a Class object for the superclass of the class for the
current Class object. For example, for the Class object objectType for
the variable pet we just defined, this would return a Class object for the
class Animal . You could output the name of the superclass with the
statement:
System.out.println(pet.getClass().getSuperclass().getName());
Where your class is not a derived class, the method will return a Class
object for the class Object .
isInterface()
This method returns true if the current Class object represents an
interface. We will discuss interfaces a little later in this chapter.
getInterface()
This method will return an array of Class objects that represent the
interfaces implemented by the class. We will investigate interfaces later in
this chapter.
toString()
This method returns a String object representing the current Class
object. For example, the Class object, objectType , corresponding to the
pet variable we created would output:
class Duck
This is not an exhaustive list. There are a number of other methods defined in the class Class that
enable you to find out details of the contents of a class - the fields or data members in other words, the
public methods defined in the class, even the classes defined in the class. If you need this kind of
capability you can find out more by browsing the API documentation that comes with the JDK.
Although you can use the forName() method in the table above to get the Class object
corresponding to a particular class type, there is a more direct way. If you append .class to the name
of any class, you have a reference to the Class object for that class. For example, String.class
references the Class object for the String class and Duck.class references the Class object for
our Duck class. This may not seem particularly relevant at this point, but keep it in mind. We will need
to use this later on when we get to explore the capabilities of the Java Sound API. Because there is only
one Class object for each class or interface type, you could test for the class of an object
programmatically. Given a variable, pet, of type Animal , we could check whether the object referenced
was of type Duck with the statement:
if(pet.getClass()==Duck.class)
System.out.println("By George - it is a duck!");
This tests whether the object referenced by pet is of type Duck . Because each Class object is unique,
this is a precise test. If pet contained a reference to an object that was a subclass of Duck , the result of
the comparison in the if would be false . We will see a little later in this chapter that we have an
operator in Java, instanceof , that does almost the same thing - but not quite.
Search WWH ::




Custom Search