Java Reference
In-Depth Information
class A {
int i = 7 ;
public A() {
setI( 20 );
System.out.println( "i from A is " + i);
}
public void setI( int i) {
this .i = 2 * i;
}
}
class B extends A {
public B() {
System.out.println( "i from B is " + i);
}
public void setI( int i) {
this .i = 3 * i;
}
}
11.9 Casting Objects and the instanceof Operator
One object reference can be typecast into another object reference. This is called cast-
ing object.
Key
Point
casting object
In the preceding section, the statement
m( new Student());
assigns the object new Student() to a parameter of the Object type. This statement is
equivalent to
Object o = new Student(); // Implicit casting
m(o);
The statement Object o = new Student() , known as implicit casting , is legal because an
instance of Student is an instance of Object .
Suppose you want to assign the object reference o to a variable of the Student type using
the following statement:
implicit casting
Student b = o;
In this case a compile error would occur. Why does the statement Object o = new Stu-
dent() work but Student b = o doesn't? The reason is that a Student object is always an
instance of Object , but an Object is not necessarily an instance of Student . Even though
you can see that o is really a Student object, the compiler is not clever enough to know it. To
tell the compiler that o is a Student object, use explicit casting . The syntax is similar to the
one used for casting among primitive data types. Enclose the target object type in parentheses
and place it before the object to be cast, as follows:
explicit casting
Student b = (Student)o; // Explicit casting
It is always possible to cast an instance of a subclass to a variable of a superclass (known as
upcasting ), because an instance of a subclass is always an instance of its superclass. When
casting an instance of a superclass to a variable of its subclass (known as downcasting ), explicit
upcasting
downcasting
 
 
 
Search WWH ::




Custom Search