Given the statement
A m = new B开发者_开发问答();
and knowing that class B is a subclass of class A and A is a subclass of Object, explain what happens when the statement is evaluated.
Many thanks in advance!
The simplest answer is that since B is a subclass of A, this evaluation can occur normally.
A pointer to a base class can point to a derived class just fine, since the derived class is an instance of the base class.
Let's expand the example a bit more:
A m;
B n = new B();
m = n; // Valid statement
m = n is a valid statement because we can only assign an A object to m. The compiler sees that B derives from A, so it is in actuality an A object. If it were an unrelated type, the compiler would yell at you.
- A variable called
m
is created, of typeA
- An object of type
B
is constructed - The variable
m
is assigned a reference to the created object
You can refer to m
as if it is of type A
without a cast. This means that you can call any methods that are defined in A
; if they are overridden, B
's version of the method is called instead. You cannot call any methods that are specific to B
, however, unless you use a cast.
RTTI
is the word. Run-Time Type Identifications.
I recommend you "Thinking in Java" by Bruce Eckel
精彩评论