This week's book giveaway is in the OCAJP 8 forum. We're giving away four copies of OCA Java SE 8 Programmer I Study Guide and have Edward Finegan & Robert Liguori on-line! See this thread for details.
Suppose I have two car objects. Each car has a radio, an engine, and other parts. Even though an engine object isn't a car, it is related to car because it is a subcomponent of a car. If I make a reference to engine, how do I know which engine I am referencing? Car A or Car B? Is there anyway to link each engine object to it's individual car object even though engine can't be a subclass of car?
It seems that you are confusing "has-a" with "is-a". The first are usually attributes. The second is a subclass.
What you are describing is more like
Now carA will be able to access its own engine and radio and carB will have a different engine and radio.
JavaBeginnersFaq "Yesterday is history, tomorrow is a mystery, and today is a gift; that's why they call it the present." Eleanor Roosevelt
Marilyn de Queiroz
Joined: Jul 22, 2000
Each of these involves an "is-a" relationship. [ November 17, 2003: Message edited by: Marilyn de Queiroz ]
Joined: Nov 17, 2003
Thanks for the reply Marilyn, Are the radio and engine classes on the same hierarchial level as car, but since they are declared inside car, they become linked to car? If I created the classes inside car is that when they would become subclasses?
The "is-a" relationship is defined by use of the "extends" keyword when declaring a class. You'll notice that in Marilyn's second post every class is defined in terms of another class:
This syntax says that "Truck" is a subclass of "MotorizedVehicle" (or that "MotorizedVehicle" is a superclass of "Truck"). So it's not where the classes are defined. They can be in separate files, and even in separate packages. But the "extends" indicates the parent<-->child nature of the "is-a" relationship. A "Truck" is-a "MotorizedVehicle". The "has-a" relationship is one of composition. As in Marilyn's first example, you wouldn't say that a "Radio" is-a "Car" or an "Engine" is-a "Car". A "Car" has-a "Radio" and a "Car" has-a(n) "Engine". This is specified by creating instance variables in the class definition. The "Car" class declares two variables, one of type "Radio" and one of type "Engine", just as it might declare a variable, "int numDoors" to keep track of how many doors it has. "Engine" and "Radio" are no different than "int" here: they specify the type of the variable.
Joined: Nov 17, 2003
Radio and Engine are still objects, though, since they have their own classes. In other words, I can create methods and variables for instances of engine and radio. I think I understand, thanks for the help.