Java Reference
In-Depth Information
// Can assign a reference of an object of the Object class
obj = new Object();
// Can assign a reference of an object of the Account class
Account act = new Account();
obj = act;
// Can assign a reference of object of any class. Assume that the AnyClass class exists
obj = new AnyClass();
The opposite of the above rule is not true. You cannot assign a reference of an object of the Object class to a
reference variable of any other type. The following statement is not valid:
Account act = new Object(); // A compile-time error
Sometimes, you may store the reference of an object of a specific type, say Account type, in a reference variable of
the Object type, and later you would like to assign the same reference back to a reference variable of the Account type.
You can do so by using a cast as shown:
Object obj2 = new Account();
Account act = (Account)obj2; // Must use a cast
Sometimes you may not be sure that a reference variable of the Object class holds a reference to an object of a
specific type. In those situations, you need to use the instanceof operator to test. The left operand of the instanceof
operator is a reference variable and its right operand is a class name. If its left operand is a reference of its right
operand type, it returns true . Otherwise, it returns false . Please refer to the chapter on inheritance for more detailed
discussion on the instanceof operator.
Object obj;
Cat c;
/* Do something here and store a reference in obj... */
if (obj instanceof Cat) {
// If we get here, obj holds a reference of a Cat for sure
c = (Cat)obj;
}
You will need to make use of this rule when you have a method that takes an Object as a parameter. You can pass
a reference of any object for the parameter of the Object class. Consider the following snippet of code that shows a
method declaration:
public void m1(Object obj) {
// Code goes here
}
You can call m1() in a number of different ways:
m1(null); // Pass null reference
m1(new Object()); // Pass a reference of an object of the Object class
m1(new AnyClass()); // Pass a reference of an object of the AnyClass class
 
Search WWH ::




Custom Search