<< Chapter < Page | Chapter >> Page > |
Such an assignment does not require the use of a cast operator.
Type Object is completely generic
A reference to any object can be assigned to a reference variable of the type Object , because the Object class is a superclass of every other class.
Converting reference types with a cast
Assignments of references, other than those listed above , require the use of a cast operator to purposely change the type of the reference.
Doesn't work in all cases
However, it is not possible to perform a successful cast to convert the type of a reference in all cases.
Generally, a cast can only be performed among reference types that fall on the same ancestral line of the class hierarchy, or on an ancestral line of an interface hierarchy. For example, a reference cannot be successfully cast to the type of a sibling or a cousin in the class hierarchy.
Downcasting
When we cast a reference along the class hierarchy in a direction from the root class Object toward the leaves, we often refer to it as a downcast .
While it is also possible to cast in the direction from the leaves to the root, this happens automatically, and the use of a cast operator is not required.
A sample program
The program named Poly02 , shown in Listing 11 near the end of the module, illustrates the use of the cast operator with references.
When you examine that program, you will see that two classes named A and C each extend the class named Object . Hence, we might say that they are siblings in the class hierarchy.
Another class named B extends the class named A . Thus, we might say that A is a child of Object , and B is a child of A .
The class named A
The definition of the class named A is shown in Listing 1 . This class extends the class named Object .
(Recall that it is not necessary to explicitly state that a class extends the class named Object . Any class that does not explicitly extend some other class will automatically extend Object by default. The class named A is shown to extend Object here simply for clarity of presentation.)
Listing 1 . Definition of the class named A. |
---|
class A extends Object{
//this class is empty}//end class A |
The class named A is empty. It was included in this example for the sole purpose of adding a layer of inheritance to the class hierarchy.
The class named B
Listing 2 shows the definition of the class named B . This class extends the class named A .
Listing 2 . Definition of the classnamed B. |
---|
class B extends A{
public void m(){System.out.println("m in class B");
}//end method m()}//end class B |
The method named m()
Notification Switch
Would you like to follow the 'Object-oriented programming (oop) with java' conversation and receive update notifications?