<< Chapter < Page | Chapter >> Page > |
Program: Inheritance03.java
// Learning Object Inheritance03
// dynamic dispatchingclass Particle {
int position;
Particle(int p) { position = p;
}
void newPosition(int delta) { position = position + delta;
}}
class AParticle extends Particle {
double spin;
AParticle(int p, double s) { super(p);
spin = s; }
void newPosition(int delta) {
if (spin < delta)
position = position + delta; }
}
class BParticle extends Particle { int charge;
BParticle(int p, int c) {
super(p); charge = c;
}}
class CParticle extends BParticle {
boolean strange;
CParticle(int p, int c, boolean s) { super(p, c);
strange = s; }
void newPosition(int delta) {
if (strange) position = position * charge;
}}
class Inheritance03 {
public static void main(/*String[] args*/) {
Particle p = new Particle(10); AParticle a = new AParticle(20, 2.0);
BParticle b = new BParticle(30, 3); CParticle c = new CParticle(40, 4, true);
p.newPosition(10);
int pPosition = p.position; p = a;
p.newPosition(10); int aPosition = p.position;
p = b; p.newPosition(10);
int bPosition = p.position; p = c;
p.newPosition(10); int cPosition = p.position;
}}
p
,
and then the method
newPosition
is invoked using
p
. The modified
value of
position
is assigned to a variable.p
invokes the method defined in class
Particle
.a
to
p
, check that the call invokes the
method defined in the class
AParticle
; this method overrides the method declared
in class
Particle
. Although the type of
p
is class
Particle
, it holds a reference to an object whose type is
class
AParticle
so the method of that class is called.Particle
has become garbage.b
to
p
, check that the call invokes the
method defined in the superclass
Particle
; since the method was
not overridden in
BParticle
, the method called is the one inherited from the
superclass.c
to
p
, check that the call invokes the
method defined in the class
CParticle
; this method overrides the method declared
in class
Particle
. Although the type of
p
is class
Particle
, it holds a reference to an object whose type is
class
CParticle
so the method of that class is called.
Exercise Add an assignment of
c
to
b
and call
b.newPosition(10)
. What is the value now of
b.position
?
Concept A variable of the type of a class can reference an object of the type of a subclass , but this variable cannot be used to access fields declared in the subclass.Nevertheless, the object “remembers” its type, even if it is assigned to a variable of the type of its superclass, and the type can be “recovered”by casting to a variable of the type of the subclass. This is called downcasting because the cast is “down” the derivation hierarchy.
Notification Switch
Would you like to follow the 'Learning objects for java (with jeliot)' conversation and receive update notifications?