What are the Object and Class classes used for?
Object class
Object is a Superclass for all class
The Object class, in the java.lang package, sits at the top of the class hierarchy tree. Every class is a descendant, direct or indirect, of the Object class. Every class you use or write inherits the instance methods of Object. You need not use any of these methods, but, if you choose to do so, you may need to override them with code that is specific to your class. The methods inherited from Object that are discussed in this section are:
– protected Object clone() throws CloneNotSupportedException : Creates and returns a copy of this object.
– public boolean equals(Object obj) : Indicates whether some other object is “equal to” this one.
– protected void finalize() throws Throwable : Called by the garbage collector on an object when garbage collection determines that there are no more references to the object
– public final Class getClass() : Returns the runtime class of an object.
– public int hashCode() : Returns a hash code value for the object.
– public String toString() : Returns a string representation of the object.
The notify, notifyAll, and wait methods of Object all play a part in synchronizing the activities of independently running threads in a program.
There are five of these methods:
public final void notify()
public final void notifyAll()
public final void wait()
public final void wait(long timeout)
public final void wait(long timeout, int nanos)
Class class
public final class Class<T> extends Object
implements Serializable, GenericDeclaration, Type, AnnotatedElement
Instances of the class Class represent classes and interfaces in a running Java application. An enum is a kind of class and an annotation is a kind of interface. Every array also belongs to a class that is reflected as a Class object that is shared by all arrays with the same element type and number of dimensions.
The primitive Java types (boolean, byte, char, short, int, long, float, and double), and the keyword void are also represented as Class objects.
Class has no public constructor. Instead Class objects are constructed automatically by the Java Virtual Machine as classes are loaded and by calls to the defineClass method in the class loader.
The following example uses a Class object to print the class name of an object:
void printClassName(Object obj) {
System.out.println("The class of " + obj +
" is " + obj.getClass().getName());
}
It is also possible to get the Class object for a named type (or for void) using a class literal.
For example:
System.out.println("The name of class Employee is: "+Employee.class.getName());
Recent Comments