Saturday, October 9, 2010

Object Class In Java

HI ,
Object Class :

The Object class sits at the top of the class hierarchy tree in the Java development environment. Every class in the Java system is a descendent (direct or indirect) of the Object class. The Object class defines the basic state and behavior that all objects must have, such as the ability to compare oneself to another object, to convert to a string, to wait on a condition variable, to notify other objects that a condition variable has changed, and to return the object's class.

The equals Method

Use the equals to compare two objects for equality. This method returns true if the objects are equal, false otherwise. Note that equality does not mean that the objects are the same object. Consider this code that tests two Integers, one and anotherOne, for equality:
Integer one = new Integer(1), anotherOne = new Integer(1);  if (one.equals(anotherOne))     System.out.println("objects are equal"); 
This code will display objects are equal even though one and anotherOne reference two different, distinct objects. They are considered equal because they contain the same integer value.

Your classes should override this method to provide an appropriate equality test. Your equals method should compare the contents of the objects to see if they are functionally equal and returntrue if they are.

The getClass Method

The getClass method is a final method (cannot be overridden) that returns a runtime representation of the class of this object. This method returns a Class object. You can query the Classobject for a variety of information about the class, such as its name, its superclass, and the names of the interfaces that it implements. The following method gets and displays the class name of an object:
void PrintClassName(Object obj) {     System.out.println("The Object's class is " + obj.getClass().getName()); } 
One handy use of the getClass method is to create a new instance of a class without knowing what the class is at compile time. This sample method creates a new instance of the same class asobj which can be any class that inherits from Object (which means that it could be any class):
Object createNewInstanceOf(Object obj) {     return obj.getClass().newInstance(); }



No comments:

AWS certification question

AWS AWS Hi! this is for questions related to AWS questions. EC2 instances EC2 storage types cold HDD : 1. Defines performance in terms...