A Lesson in Objects

   

As you work, you interact with objects all the time. Phones, computers, fax machines, handheld devices, and cars are all examples of objects in the real world. When you deal with these objects, you don't separate an object from its attributes and its operations. For example, when you drive your car, you don't think about its attributes (such as its current speed of travel) apart from the operations (such as accelerating in response to increased pressure on the gas pedal). You put your car in gear, adjust the speed using the gas pedal, and drive. Every aspect is part of a single, cohesive package.

By using object-oriented programming, you can approach the same simplicity of use. A structured programmer is accustomed to creating data structures to hold attributes and then defining separate functions to manipulate this data. Objects, however, combine the data with the code that manipulates it. This results in self-contained units that hold everything necessary to define an object's state and work with it.

To continue the preceding example, when you describe a car and its current state, there are a number of important physical attributes: the speed it is traveling, the amount of horse-power the engine has, the drag coefficient associated with its body, the number of doors it has, and so on. In addition, the car has several associated functions: It accelerates, decelerates, turns, and shifts gears. Neither the physical nor the functional definitions alone complete the definition of a car ”it is necessary to define them both.

Traditional Program Design

To manipulate information about cars using a traditional programming approach, you might define a data structure called MyCarData that looks something like this:

 public class MyCarData {   float speed;   int hp;   double dragCoef;   int numDoors; } 

Then you would create a set of functions to operate on the data that is completely separate from the declaration for MyCarData:

 public void speedUp(MyCarData m){     ...   }   public void slowDown(MyCarData m){     ...   }   public void stop(MyCarData m){     ...   } 

Here the only link between these functions and the data they operate on is through a function parameter. Whenever changes to MyCarData are required, a programmer must search for all such uses of the data structure because there is no natural grouping imposed by the structure of the code. It is also difficult for a programmer working on MyCarData to know if all its attributes are even needed by the programs that use it because of this separation.

The OOP Way

In OOP, the attributes maintained for a car and the methods needed to work with it are combined into a single object:

 public class Car {   float speed;   int hp;   double dragCoef;   int numDoors;   public void speedUp() {     speed += 1;   }   public void slowDown() {     speed -= speed * dragCoef;   }   public void stop() {     speed=0;   } } 

Here the variables and methods are grouped together to form a single view of a car and what can be done with it in a program. Within each of these methods, there is no need to pass in a reference to a data structure variable. The methods implicitly know about the variables of their own class and have full access to them.

Extending Objects Through Inheritance

Many of the benefits of OOP are achieved when objects are defined so that they inherit the functionality of objects that already exist. Given this, the next step in this overview of developing objects is to create multiple objects based on one super object. Return to the preceding car example. A Saturn SL 2 is a car, and yet certainly it has several attributes that not all cars have. When building a car, manufacturers don't typically start from scratch. They know their cars are going to need several things: tires, doors, steering wheels, and more. Frequently, the same parts can be used between cars. Wouldn't it be nice to start with a generic car, build up the specifics of a Saturn, and from there (because each Saturn has its own peculiarities ) build up the SL 2?

Inheritance is a feature of OOP programming that enables you to do just that. By inheriting all the general features of a car into a Saturn, it isn't necessary to reinvent the common functionality and attributes every time a new model of car is needed. The details of inheritance in Java are described in Chapter 7, "Classes," but you'll get just enough information here to give you a head start toward thinking in an object-oriented way.

By inheriting a car's features into the Saturn ”through an added benefit called polymorphism ”it can be treated generically as a car whenever the unique features that make it a Saturn are unimportant. Now that might seem obvious, but the implications of that fact are enormous . Under traditional programming techniques, you would have to separately deal with each type of car ”Fords here, GMCs there, and so on. Under OOP, the features that all cars have are encapsulated within the Car object. When you inherit Car into Ford, GMC, and Saturn, you can reuse the common functionality provided by Car without any extra work or redundant programming.

Note

When you use inheritance to build a more specific type of object, such as Saturn, from a general type, such as Car, you can describe the relationship using the terminology "Saturn inherits from Car" or "Saturn extends Car."


For example, assume you have a racetrack program. On the racetrack, you have a green light, yellow light, and red light. Now, each racecar driver comes to the track with a different type of car. Each driver has accessible to him each of the peculiarities of his individual car (such as a CD player in a Saturn SL2, or some fancy accelerator found in a Lamborghini Diablo). As you put each car on the track, you provide a reference to the car to the track itself. The track controller doesn't need access to any methods that access that fancy Lamborghini accelerator or the Saturn's CD player; those methods are individual to each of the cars. However, the person sitting in the control tower does want to be able to tell every driver to slow down when the yellow light is illuminated. Because this requirement is common to all car types, the associated functionality can be defined in Car, inherited by each of the particular car makes, and used by the control tower program accordingly . Look at this hypothetical code.

Here are two types of cars with their unique features defined:

 class LamborghiniDiablo extends Car {   public void superCharge() {     for (int x=0; x<infinity; x++)       speedUp();   } } class SaturnSL2 extends Car {   CDPlayer cd;   public void goFaster() {     while(I_Have_Gas) {       speedUp();     }   }   public void entertain() {     cd.turnOn();   } } 

Here is the race track itself:

 class RaceTrack {   Car theCars[] = new Car[3];   int numberOfCars = 0;   public void addCar(Car newCar) {     theCars[numberOfCars]=newCar;     numberOfCars++;   }   public void yellowLight() {     for (int x=0; x<numberOfCars; x++)       theCars[x].slowDown();   } } 

Here is the program that puts it all together:

 class RaceProgram {   LamborghiniDiablo me = new LamborghiniDiablo();   SaturnSL2 you = new SaturnSL2();   RaceTrack rc = new RaceTrack();   public void start() {     rc.addCar(me);     rc.addCar(you);     while(true) {       if (somethingIsWrong)         rc.yellowLight();     }   } } 

This works because in the RaceProgram class, you created two different objects: me (of type LamborghiniDiablo ) and you (of type SaturnSL2 ). You can call rc.addCar, which takes a Car as a parameter type, because of polymorphism (see Chapter 7). Because both of the cars extended Car, they can be used as Car s as well as their individual types. This means that if you create yet another type of car ( VolvoS80 ), you could call rc.addCar(theVolvo) without having to make any changes to RaceTrack whatsoever. Notice that this is true even though SaturnSL2 effectively is a different structure because it now also contains a CDPlayer variable.

   


Special Edition Using Java 2 Standard Edition
Special Edition Using Java 2, Standard Edition (Special Edition Using...)
ISBN: 0789724685
EAN: 2147483647
Year: 1999
Pages: 353

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net