Previous    Next

CLASS EXTENSION

Program 14.1 illustrates the use of class extension in Java. Every Vehicle is an Object;every Car is a Vehicle; thus every Car is also an Object. Every Vehicle (and thus every Car and Truck) has an integer position field and a move method.

An object-oriented program.
class Vehicle {
 int position;
 void move (int x) { position = position + x; }
}
class Car extends Vehicle{
 int passengers;
 void await(Vehicle v) {
 if (v.position < position)
 v.move(position - v.position);
 else
 this.move(10);
 }
}
class Truck extends Vehicle{
 void move(int x) {
 if (x <= 55) { position = position + x; }
 }
}
class Main{
 public static void main(String args[]) {
 Truck t = new Truck();
 Car c = new Car();
 Vehicle v = c;
 c.passengers = 2;
 c.move(60);
 v.move(70);
 c.await(t);
 }
}



Java End example

In addition, a Car has an integer passengers field and an await method. The variables in scope on entry to await are

passengers because it is a field of Car,
position because it is (implicitly) a field of Car,
v because it is a formal parameter of await,
this because it is (implicitly) a formal parameter of await.


At the call to c.await(t), the truck t is bound to the formal parameter v of the await method. Then when v.move is called, this activates the Truck_move method body, not Vehicle_move.

We use the notation A_m to indicate a method instance m declared within aclass A. This is not part of the Java syntax, it is just for use in discussing the semantics of Java programs. Each different declaration of a method is a different method instance. Two different method instances could have the same method name if, for example, one overrides the other.


JaVaScreenshot Previous    Next
Comments