Java Reference
In-Depth Information
11.22
Show the output of following program:
1
public class
Test {
2
public static void
main(String[] args) {
3 A a =
new
A(
3
);
4 }
5 }
6
7
class
A
extends
B {
8
public
A(
int
t) {
9 System.out.println(
"A's constructor is invoked"
);
10 }
11 }
12
13
class
B {
14
public
B() {
15 System.out.println(
"B's constructor is invoked"
);
16 }
17 }
Is the no-arg constructor of
Object
invoked when
new A(3)
is invoked?
One object reference can be typecast into another object reference. This is called
casting object.
Key
Point
In the preceding section, the statement
casting object
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 casting must be used to confirm your intention to the compiler with the
upcasting
downcasting