Driver and car class: where would I write drive() method? - oop

Here's a model in reference to my question:
O-O model
When implementing the code, I imagine myself writing a class for "Driver", and another for "Car". If I were to write a method (drive car, operate wipers, apply breaks, etc), is it recommended that I write them in the Driver class file or Car file?

Your diagram shows where the methods should go. Which is in the Car class.
BUT, I would slightly change your method calls:
break()
releaseBreak()
turnOnWipers()
turnOffWipers()
But overall it would be the driver that calls those methods on the car.
BTW, it doesn't HAVE to be a Driver driving the Car, just something that knows about a Car's interface and how to interact with it. Think self driving cars, etc...

Related

How does polymorphism make my code more flexible?

I am reading Head First Object Oriented Design to get a better understanding of OOP concepts.
Polymorphism is explained as:
Airplane plane = new Airplane();
Airplane plane = new Jet();
Airplane plane = new Rocket();
You can write code that works on the superclass, like an airplane, but will work with any of the subclasses. :- * Hmmm.. ..I got this one.*.
It further explains:
-> So how does polymorphism makes code flexible?
Well, if you need new functionality, you could write a new subclass of
AirPlane. But since your code uses the superclass, your new class will work
without any changes to the rest of your code.
Now I am not getting it. I need to create a sublass of an airplane. For example: I create a class, Randomflyer. To use it I will have to create its object. So I will use:
Airplane plane = new Randomflyer();
I am not getting it. Even I would have created an object of a subclasses directly. Still I don't see a need to change my code anywhere when I will add a new subclass. How does using a superclass save me from making extra changes to the rest of my code?
Say you have the following (simplified):
Airplane plane = new MyAirplane();
Then you do all sorts of things with it:
List<Airplane> formation = ...
// superclass is important especially if working with collections
formation.add(plane);
// ...
plane.flyStraight();
plane.crashTest();
// ... insert some other thousand lines of code that use plane
Thing is. When you suddenly decide to change your plane to
Airplane plane = new PterdodactylSuperJet();
all your other code I wrote above will just work (differently, of course) because the other code relies on the interface (read:public methods) provided by the general Airplane class, and not from the actual implementation you provide at the beginning. In this way, you can pass on different implementations without altering your other code.
If you hadn't used an Airplane superclass and just written MyAirplane and PterdodactylSuperJet in the sense that you replace
MyAriplane plane = new MyAirplane();
with
PterdodactylSuperJet plane = new PterdodactylSuperJet();
then you have a point: the rest of your code may still work. But that just happens to work, because you wrote the same interface (public methods) in both classes, on purpose. Should you (or some other dev) change the interface in one class, moving back and forth between airplane classes will render your code unusable.
Edit
By on purpose I mean that you specifically implement methods with the same signatures in both MyAirplane and PterodactylSuperJet in order for your code to run correctly with both. If you or someone else change the interface of one class, your flexibility is broken.
Example. Say you don't have the Airplane superclass and another unsuspecting dev modifies the method
public void flyStraight()
in MyAirplane to
public void flyStraight (int speed)
and assume your plane variable is of type MyAirplane. Then the big code would need some modifications; assume that's needed anyway. Thing is, if you move back to a PterodactylSuperJet (e.g. to test it, compare it, a plethora of reasons), your code won't run. Whygodwhy. Because you need to provide PterodactylSuperJet with the method flyStraight(int speed) you didn't write. You can do that, you can repair, that's alright.
That's an easy scenario. But what if
This problem bites you in the ass a year after the innocent modification? You might even forget why you did that in the first place.
Not one, but a ton of modificatios had occurred that you can't keep track of? Even if you can keep track, you need to get the new class up to speed. Almost never easy and definitely never pleasant.
Instead of two plane classes you have a hundred?
Any linear (or not) combination of the above?
If you had written an Airplane superclass and made each subclass override its relevant methods, then by changing flyStraight() to flyStraight(int) in Airplane you would be compelled to adapt all subclasses accordingly, thus keeping consistency. Flexibility will therefore not be altered.
End edit
That's why a superclass stays as some kind of "daddy" in the sense that if someone modifies its interface, all subclasses will follow, hence your code will be more flexible.
A very simple use-case to demonstrate the benefit of polymorphism is batch processing of a list of objects without really bothering about its type (i.e. delegating this responsibility to each concrete type). This helps performing abstract operations consistently on a collection of objects.
Let's say you want to implement a simulated flight program, where you would want to fly each and every type of plane that's present in your list. You simply call
for (AirPlane p : airPlanes) {
p.fly();
}
Each plane knows how to fly itself and you don't need to bother about the type of the planes while making this call. This uniformity in the behaviour of the objects is what polymorphism gives you.
Other people have more fully addressed your questions about polymorphism in general, but I want to respond to one specific piece:
I am not getting it, even I would have create an object of subclasses
directly.
This is actually a big deal, and people go to a lot of effort to avoid doing this. If you crack open something like the Gang of Four, there are a bunch of patterns dedicated to avoiding just this issue.
The main approach is called the Factory pattern. That looks something like this:
AirplaneFactory factory = new AirplaneFactory();
Airplane planeOne = factory.buildAirplane();
Airplane planeTwo = factory.buildJet();
Airplane planeThree = factory.buildRocket();
This gives you more flexibility by abstracting away the instantiation of the object. You might imagine a situation like this: your company starts off primarily building Jets, so your factory has a buildDefault() method that looks like:
public Airplane buildDefault() {
return new Jet();
}
One day, your boss comes up to you and tells you that the business has changed. What people really want these days are Rockets -- Jets are a thing of the past.
Without the AirplaneFactory, you'd have to go through your code and replace possibly dozens of calls to new Jet() with new Rocket(). With the Factory pattern, you can just make a change like:
public Airplane buildDefault() {
return new Rocket();
}
and so the scope of the change is dramatically reduced. And since you've been coding to the interface Airplane rather than the concrete type Jet or Rocket, this is the only change you need to make.
Suppose you have methods in your Controller class of Planes like
parkPlane(Airplane plane)
and
servicePlane(Airplane plane)
implemented in your program. It will not BREAK your code.
I mean, it need not to change as long as it accepts arguments as AirPlane.
Because it will accept any Airplane despite of actual type, flyer, highflyr, fighter, etc.
Also, in a collection:
List<Airplane> plane; // Will take all your planes.
The following example will clear your understanding.
interface Airplane{
parkPlane();
servicePlane();
}
Now your have a fighter plane that implements it, so
public class Fighter implements Airplane {
public void parkPlane(){
// Specific implementations for fighter plane to park
}
public void servicePlane(){
// Specific implementatoins for fighter plane to service.
}
}
The same thing for HighFlyer and other clasess:
public class HighFlyer implements Airplane {
public void parkPlane(){
// Specific implementations for HighFlyer plane to park
}
public void servicePlane(){
// specific implementatoins for HighFlyer plane to service.
}
}
Now think your controller classes using AirPlane several times,
Suppose your Controller class is AirPort like below,
public Class AirPort{
AirPlane plane;
public AirPlane getAirPlane() {
return airPlane;
}
public void setAirPlane(AirPlane airPlane) {
this.airPlane = airPlane;
}
}
here magic comes as Polymorphism makes your code more flexible because,
you may make your new AirPlane type instances as many as you want and you are not changing
code of AirPort class.
you can set AirPlane instance as you like (Thats called dependency Intection too)..
JumboJetPlane // implementing AirPlane interface.
AirBus // implementing AirPlane interface.
Now think of If you create new type of plane, or you remove any type of Plane does it make difference to your AirPort?
No, Because we can say the The AirPort class refers the AirPlane polymorphically.
As far as I understand, the advantage is that, for example, in a airplane combat game, you have to update all airplanes' positions at every loop, but you have several different airplanes. Let's say you have:
MiG-21
Waco 10
Mitsubishi Zero
Eclipse 500
Mirage
You don't want to have to update their movements and positions in separate like this:
Mig21 mig = new Mig21();
mig.move();
Waco waco = new Waco();
waco.move();
Mitsubishi mit = new Mitsubishi();
mit.move();
...
You want to have a superclass that can take any of this subclasses (Airplane) and update all in a loop:
airplaneList.append(new Mig21());
airplaneList.append(new Waco());
airplaneList.append(new Mitsubishi());
...
for(Airplane airplane : airplanesList)
airplane.move()
This makes your code a lot simpler.
You are completely correct that sub-classes are only useful to those who instantiate them. This was summed up well by Rich Hickey:
...any new class is itself an island; unusable by any existing code written by anyone, anywhere. So consider throwing the baby out with the bath water.
It is still possible to use an object which has been instantiated somewhere else. As a trivial example of this, any method which accepts an argument of type "Object" will probably be given an instance of a sub-class.
There is another problem though, which is much more subtle. In general a sub-class (like Jet) will not work in place of a parent class (like Airplane). Assuming that sub-classes are interchangable with parent classes is the cause of a huge number of bugs.
This property of interchangability is known as the Liskov Substitution Principle, and was originally formulated as:
Let q(x) be a property provable about objects x of type T. Then q(y) should be provable for objects y of type S where S is a subtype of T.
In the context of your example, T is the Airplane class, S is the Jet class, x are the Airplane instances and y are the Jet instances.
The "properties" q are the the results of the instances' methods, the contents of their properties, the results of passing them to other operators or methods, etc. We can think of "provable" as meaning "observable"; ie. it doesn't matter if two objects are implemented differently, if there is no difference in their results. Likewise it doesn't matter if two objects will behave differently after an infinite loop, since that code can never be reached.
Defining Jet as a sub-class of Airplane is a trivial matter of syntax: Jet's declaration must contain the extends Airplane tokens and there mustn't be a final token in the declaration of Airplane. It is trivial for the compiler to check that objects obey the rules of sub-classing. However, this doesn't tell us whether Jet is a sub-type of Airplane; ie. whether a Jet can be used in place of an Airplane. Java will allow it, but that doesn't mean it will work.
One way we can make Jet a sub-type of Airplane is to have Jet be an empty class; all of its behaviour comes from Airplane. However, even this trivial solution is problematic: an Airplane and a trivial Jet will behave differently when passed to the instanceof operator. Hence we need to inspect all of the code which uses Airplane to make sure that there are no instanceof calls. Of course, this goes completely against the ideas of encapsulation and modularity; there's no way we can inspect code which may not even exist yet!
Normally we want to sub-class in order to do something differently to the superclass. In this case, we have to make sure that none of these differences is observable to any code using Airplane. This is even more difficult than syntactically checking for instanceof; we need to know what all of that code does.
That's impossible due to Rice's Theorem, hence there's no way to check sub-typing automatically, and hence the amount of bugs it causes.
For these reasons, many see sub-class polymorphism as an anti-pattern. There are other forms of polymorphism which don't suffer these problems though, for example "parameteric polymorphism" (referred to as "generics" in Java).
Liskov Substitution Principle
Comparison between sub-classing and sub-typing
Parameteric polymorphism
Arguments against sub-classing
Rice's theorem
One good example of when polymorphism is useful:
Let us say you have abstract class Animal, which defines methods and such common to all animals, such as makeNoise()
You then could extend it with subclasses such as Dog, Cat, Tiger.
Each of these animals overrides the methods of the abstract class, such as makeNoise(), to make these behaviors specific to their class. This is good because obiously each animal makes a different noise.
Here is one example where polymorphism is a great thing: collections.
Lets say I have an ArrayList<Animal> animals, and it is full of several different animals.
Polymorphism makes this code possible:
for(Animal a: animals)
{
a.makeNoise();
}
Because we know that each subclass has a makeNoise() method, we can trust that this will cause each animal object to call their specific version of makeNoise()
(e.g. the dog barks, the cat meows, the cow moos, all without you ever even having to worry about which animal does what.)
Another advantage is apparent when working with a team on a project. Let's say another developer added several new animals without ever telling you, and you have a collection of animals which now has some of these new animal types (which you dont even know exist!). You can still call the makeNoise() method (or any other method in the animal superclass) and trust that each type of animal will know what to do.
The nice thing about this animal superclass is that you can a extend a superclass and make as many new animal types as you want, without changing ANYTHING in the superclass, or breaking any code.
Remember the golden rule of polymorphism. You can use a subclass anywhere a superclass type object is expected.
For example:
Animal animal = new Dog;
It takes a while to learn to think polymorphically, but once you learn your code will improve a lot.
Polymorphism stems from inheritance. The whole idea is that you have a general base class and more specific derived classes. You can then write code that works with the base class... and polymorphims makes your code not only work with the base class, but all derived classes.
If you decide to have your super class have a method, say getPlaneEngineType(), and you make a new child class "Jet which inherits from Plane". Plane jet = new Jet() will/can still access the superclass's getPlaneEngineType. While you could still write your own getJetEngineType() to basically override the superclass's method with a super call, This means you can write code that will work with ANY "plane", not just with Plane or Jet or BigFlyer.
I don't think that's a good example, since it appears to confuse ontology and polymorphism.
You have to ask yourself, what aspect of the behaviour of a 'Jet' is different from an 'Airplane' that would justify complicating the software to model it with a different sub-type? The book's preview cuts off after one page into the example, but there doesn't seem any rationale to the design. Always ask yourself if there is a difference in behaviour rather than just adding classes to categorise things - usually that's better done with a property value or composing strategies than with sub-classes.
An example (simplified from a major project I lead in the early noughties) would be that an Aeroplane is final but has various properties of abstract types, one of which is the engine. There are various ways of calculating the thrust and fuel use of an engine - for fast jets bi-cubic interpolation table of values of thrust and fuel rate against Mach and throttle (and pressure and humidity sometimes), for Rockets the table method but does not require compensation for stalling the air at the engine intake; for props a simpler parametrised 'bootstrap' equation can be used. So you would have three classes of AbstractAeroEngine - JetEngine, RocketEngine and BootstrapEngine which would have implementations of methods which returned thrust and fuel use rate given a throttle setting and the current Mach number. (you should almost never sub-type a non-abstract type)
Note that the differences between the types of AbstractAeroEngine, although related to the different real world engines, are entirely differences in the how the software calculates the engine's thrust and fuel use - you are not constructing an ontology of classes which describe a view of the real world, but specialising the operations performed in the software to suit specific use cases.
How does using a superclass save me from making extra changes to rest of my code?
As all your engine calculations are polymorphic, it means that when you create an aeroplane, you can bolt on whatever engine thrust calculation suits it. If you find you have to cater for another method of calculating the thrust (as we did, several times) then you can add another sub-type of AeroEngine - as long as the implementation it supplies provides the trust and fuel rate, then the rest of the system doesn't care about the internal differences - the AeroPlane class will still ask its engine for the thrust. The aeroplane only cares that it has an engine which it can use the same way as any other engine, only the creation code has to know the type of the engine to bolt onto it, and the implementation of ScramJetEngine only cares about supersonic jet calculations - the parts of AeroPlane which calculate lift and drag, and the strategy for flying it don't have to change.
Polymorphism is powerful given that when there's a need to change a behavior you can change it by overriding a method.
Your superclass inherits its properties and behaviors to your subclasses extended by it. Thus it is safe to implicitly cast an object whose type is also from its superclass. Those common methods to your subclasses make them useful to implement an API. With that, polymorphism gives you the ability to extend a functionality of your code.
Polymorphism gains properties and all behaviors and interfaces of the super class. So is the behavior of a plane really the same as a jet?

Organising refactored code

Please have a look at the code below:
public class Vehicle
'Not very well designed. Contains properties and functions/subs for cars, buses, tractors, planes, drivers etc.
end class
I am wanting to refactor the code so that there is a superclass (vehicle) and many subclasses. I want to do this as I go along whilst working on much higher priorities.
If I create the new classes then there will be two Vehicle classes i.e. the refactored vehicle and the old vehicle. I believe the best approach is to create a new namespace for the refactored code e.g. company.app.businesslogiclayer.automobiles.refactoredcode, company.app.datalogiclayer.automobiles.refactoredcode. Is this the correct approach?
I think you could treat your existing clas as a subclass since it already has some class-specific functionality in it and then look at the Extract Superclass refactoring. Here you would create your new super class and then move common features from the sub class to the super class.
Refactoring for Visual Basic has a nice section on Extract Super Class that you might find interesting.
Be careful to not overuse inheritance. "Driver" strikes me as something that you really want to use composition for. A vehicle has a driver. Similarly other things such as the might be better handled using composition. For instance you could have a car that can go 200km/h, and have one that can go 300km/h. Really do not want to have different classes for that. You could have a simple int value or a EngineBehaviour class if you have something more complex. (Keyword: strategy pattern) Also be sure to not instantiate such composite objects in your object but rather inject them (keyword: dependency injection).

What is the difference between classes and object instances?

A class is a binding of methods and variables in a single unit.
An object is an instance of a class.
These are definitions for classes and objects in programming books. My friend said that a class is a blueprint of an object. An object is a real "thing" of a blueprint. He has given an example: if Company is a class, INFOSYS, CTS, and TCS etc are objects. Whenever I think about classes and objects, these definitions confuse me. If channel is a class, what would be objects for the class? If water is a class, what would be objects of class? Can you clarify?
If channel is a class, Start Sports, BBC, and ESPN are its objects.
If water is a Class, "Fresh Lime Water" and "Soup" are its objects.
Although you might find this explanation vague, this is the answer that I could think of.
Here is how you can learn about and distinguish classes:
Say you have a class "CAR"
Its objects are Hyundai, Ford, Suzuki.
It will have the same methods but different designs -> this is how you can relate objects and classes with the real world.
A class specifies the behavior of its instances.
A class is an instance of a class too (class for a class is named a "metaclass").
A class is an abstraction. You find a class by finding generic properties applying to a group of objects.
Then a class is a template which defines the methods (behavior) and variables (state) to be included in a particular kind of object
Recognition of classes (outside classroom) requires experience.
Read anything from Alan Kay, he is the inventor of Object Technology, and one of the inventors of Smalltalk, the only pure objects environment as of today.
I'll give you a classic explanation, you can find different versions of this all over the place.
A class is like a blueprint. Say you want to build a car, the first thing you would need is a plan, This is the class. The plan will describe 'methods' such as brake and hoot. It will also describe the various components of the car. These are variables.
A car object is an instantiation of a car class. You can have lots of these for one car class.
For example:
class Car:
def __init__(self,color):
self.color = color
def hoot(self):
"do stuff"
red_car = Car('red')
red_car.hoot()
blue_car = Car('blue')
blue_car.hoot()
Now, depending on the language you are using classes themselves can be objects (this is the case in Python). Think of it this way: All blueprints have some stuff in common. That common stuff is described in the blueprint's class (which is in itself a blueprint).
Then on the point of 'water' as a class you can approach it in a few ways depending on what you want to do:
way 1:
rather have a class called Liquid with variables describing stuff like viscosity, smell, density, volume, etc. Water would be an instance of this. So would orange juice
way 2:
say you were putting together a game with a bunch of blocks that would be made up of different terrain. You could then have classes such as Grass, Water, Rock, etc (think Minecraft). Then you can have a water class instance (a water object) occupy a specific position on the map.
I do not have much programming experience, but a friend of mine made a good example of defining a class and a object.
I'll try my best to use human language as possible.
Take an horse. What makes you know that this animal is an horse and not a... dog? Because it has four legs, it's a big animal, it's very strong and it can run. Well, you just defined a 'horse' class in your head!
Now, you are going to see a white female horse called 'Pollyanna' and a black male horse called 'Demon'. As soon you see them you know that they are horses, so they belong to the 'horse' class.
What makes them different? The sex and the color... Those are properties of the 'horse' class.
'Pollyanna' and 'Demon' are two objects, they are the real thing, things you can actually touch and ride. Their properties, sex and color are also different. Pollyanna is white and female. Demon is black and male. Those defined properties are what distinguishes one object from the other. One horse from the other. But they still belong to the same class: they are always horses!
More technical now... A class is a more abstract definition of something. A blueprint. An object is the real thing that belongs to that class. When you create a new object from a class you are instantiating an object (aka creating an instance).
Hope this helps, and if it doesn't sorry... As I said before, I do not have much programming experience :)
Gianluca
In the real world, you'll often find many individual objects all of the same kind. There may be thousands of other channels in existence, all of the same make and model. Each channel was built from the same set of blueprints and therefore contains the same components. In object-oriented terms, we say that your channel is an instance of the class of objects known as channel. A class is the blueprint from which individual objects are created.
class Channel {
ChannelType type = 0;
int employeeCount = 0;
void setType(ChannelType newType) {
type = newValue;
}
void addEmployer(int increment) {
employeeCount= employeeCount+ increment;
}
void removeEmployer(int decrement) {
employeeCount= employeeCount- decrement;
}
void printStates() {
System.out.println("type :" +
type + " employee count:" + employeeCount);
}
}
The design of this class is based on the previous discussion of Channel objects. The fields typr , employeeCount represent the object's state, and the methods (setType, addEmployer, removeEmployer etc.) define its interaction with the outside world.
You may have noticed that the Channel class does not contain a main method. That's because it's not a complete application; it's just the blueprint for Channels that might be used in an application. The responsibility of creating and using new Chennel objects belongs to some other class in your application.
class Channel Demo {
public static void main(String[] args) {
// Create two different
// Channel objects
Channel BBC= new Channel ();
Channel NTV = new Channel ();
// Invoke methods on
// those objects
BBC.setType(channeltype.NEWS);
BBC.addEmployer(500);
BBC.printStates();
BBC.setType(channeltype.SPORT);
BBC.addEmployer(300);
BBC.printStates();
}
}
The output of this test prints for the two channels:
type :NEWS employee count: 500
type :SPORT employee count: 300
in grammar Common Noun is Class and Proper Noun is Object.
An object has a limited lifespan,object are created and eventually destroyed. Also during that lifetime,the object may undergo significant change
Class
A way to bind data and associated functions together.
Class have many objects.
Class is a template for creating objects.
It is logical existence.
Memory space is not allocated, when it is created.
Definition (Declaration) is created once.
Class is declared using "class" keyword.
Object
Basic runtime entity in object oriented environment.
Object belongs to only class.
Object are a implementation of class.
It is physical existence.
Memory space is allocated when it is created.
It is created many times as you required.
Object is the instance or variable of class.
Now object can be anything like bus,car,mobile or man etc.
For example take samsung smartphone.
Now samsung smartphone is an object we know that.
To create that samsung smartphone we need a blueprint(Class).
Now there are going to be thousands samsung smartphones now they can be of different color like blue or black and also they can have different ram or storage.
Now samsung smartphone with blue color, 4gb ram , 256gb storage this is one instance of that object.
So,
class - blueprint of samsung smartphone
object - samsung smartphone
instance - samsung smartphone with specific features
Class is blueprint of object and instance can be consider as single occurrence of object.
An object is an identifiable entity with some characteristics and behavior. It represents an entity that can store data and its associated function.
A class is a group of objects that share common properties and relationship. It represents a group of similar objects.
The term class and object are definetly related to ine another, but each term hold its own distinct meaning. Let's start out by explaining what the term class means. Class refers to the actuall writtten piece of code which is used to define the behaviour of any given class.so a class us a static pice of code that consists if atributes which do not change during the execution of a orogram.While Object refers to an actual instance instance of a class.Every ibhect must belong to a class

Whether to model a car object (and its parts such as engine) with has-a (composition) or is-a (inheritance)?

I am developing a class library which will include the object Car.
The dilemma is, Car itself will be a class with fields such as Registration Number, and other general information on the car.
But a car has an engine, chassis, etc. These objects need to be modelled too. Should they be classes embedded within Car? If not, what is the usage scenario of an embedded class?
I've learnt that composition is "part of", so you can model seperate classes and use the engine type, for example, at the field level of the car to achieve this. However, "aggregation", which is a "has a" relationship with the type being passed in the ctor, also applies (a car "has an" engine).
Which way do I go?
EDIT: I am currently on homework hence the lack of a reply from me. The class library is for a web app based around cars. I am a professional developer (I develop in .NET for a living but as a junior) so this is not a homework question.
Thanks
It really depends on your application.
For example, you could implement the wheels as separate classes, containing information about what tyre is on it, how worn it is, etc. but if your app doesn't even care about the wheels then the entire class is a waste of code.
I can see three use cases for composition:
The owning class has gotten overly complicated and should be broken down.
The owning class has multiple copies of a set of properties that could be mapped into a class. This allows you to bind all those properties together.
The contained object may need to be inspected or considered separately from the object that owns it (eg. you might want to move the Engine object to another car) or may be replaced as a single unit.
In summary: Use composition as a tool for encapsulating complexity or eliminating repetition. If it doesn't serve one of those purposes it probably isn't worth making a new class for.
A class should have as few responsibilities as possible and encapsulate and delegate other functionality to other classes. Lots of a small, simple classes that do one thing is a sign of a readable, stable codebase.
Yes, a car will "have" an engine, but I'd suggest using an interface for this and similar "has a" relationships. Again, depending on the professor, you might get bonus points for having a factory create different cars (appropriate, no?):
public class Car
{
private Engine engine;
public Car(Engine engine)
{
this.engine = engine;
}
public void accelerate()
{
this.engine.goFaster();
}
public void decelerate()
{
this.engine.goSlower();
}
}
public interface Engine
{
public void goFaster();
public void goSlower();
}
public class ReallyFastEngine implements Engine
{
public void goFaster()
{
// some code that goes really fast
}
public void goSlower()
{
// some code that goes slower
}
}
public class NotAsFastEngine implements Engine
{
public void goFaster()
{
// some code that goes not as fast
}
public void goSlower()
{
// some code that goes slower
}
}
public class CarFactory()
{
public static Car createFastCar()
{
return new Car(new ReallyFastEngine());
}
public static Car createNotAsFastCar()
{
return new Car(new NotAsFastEngine());
}
}
Seeing as it is homework, and depending on the inclinations of your tutor/professor/teacher, you are probably better to go down the route of writing a separate classes for the engine, wheels and so on. Even though it may be completely over-engineered, and your application may not care about them, it is possible that your homework will be marked by standards such as:
"Did they identify an engine class"
"Does it have sensible methods like Start()"
"Mark them down for lumping everything in one big class that is actually simpler, because they clearly don't understand composition"
Or whatever, and not the kinds of standards that the more pragmatic people in this thread apply to their own designs.
Only break down the model of the car into pieces that will be exposed as separate entities outside the scope of the car. Another way to think about it is do you really understand how your car gets started when you turn the key? As far as the typical driver is concerned, everything under the hood is one big (and noisy) black box. The auto-engineers know the common parts that need maintenance by the car owner and have explicitly designed them for a different level of user interaction, things like the oil dipstick or coolant reservoir refill cap.
Can you model each piece of the car? Sure. Is it helpful to model the individual spark plugs? Probably not.
Do you need cars with different attributes like color or size? Do you need cars with different capabilities like passenger or towing capacity? The one place that is different is if you need cars with different behaviors. This is where you really need to think about modeling a Driver object which has attributes, from simple ones like reaction-time to complex ones like aggressiveness.
Modeling vehicles as examples of object orientation or inheritance is problematic because the examples don't really explain the true distinctions between essential attributes that define a class. It's not new to StackOverflow but this question isn't a duplicate either, see this SO thread. I had this same discussion with a friend of mine and posted a log of it on my blog. Read up on the different aircraft types the FAA recognizes and how the regulations for each type are subdivided. There are lots of different types of aircraft, the biggest separation is between powered and unpowered.
Check out the definitions used by the FAA:
Aircraft means a device that is used
or intended to be used for flight in
the air.
Airplane means an engine-driven
fixed-wing aircraft heavier than air,
that is supported in flight by the
dynamic reaction of the air against
its wings.
Airship means an engine-driven
lighter-than-air aircraft that can be
steered.
There is also lighter-than-air and heavier-than-air. A hot-air balloon is unpowered and lighter-than-air. A blimp is powered and lighter-than-air. A glider is unpowered and heavier-than-air. A Boeing 757 is powered and heavier-than air but adds another category of 'fixed-wing' which is unlike a helicopter which is also powered and heavier-than-air but is 'rotary-wing'.
Here is the first four in the form of a table:
| Powered | Unpowered
---------------------------------------------------
Lighter-than-air | Blimp | Hot-air balloon
Heavier-than-air | 737 | Glider
You get the picture.
You can't just say you'll model the engine separately from the car because a car without an engine might be a whole different animal. A car without an engine is nothing like a trailer, which also doesn't have an engine but never will either. In these cases neither 'is-a' nor 'has-a' fits in the concrete way we build objects. You don't declare a blimp as being a aircraft that 'is-a' lighter-than-air, so is a hot-air balloon. The fact that they are both lighter-than-air doesn't make them related in any way except the physics they exploit. The distinction is important because the rules and regulations that apply are different. From the other angle, we don't describe a blimp as a hot-air balloon that 'has-a' engine. The aircraft aren't physically related, the relationship is how they should be handled.
If you don't need to define your objects to that level of detail, you may not need to model them to that level of detail either.
Car will be an top hierarchy object. Including simple fields like Number, ID or description.
And will have complicated fields like Engine, which is an object by itself.
So the Car will look something like:
class Car{
String ID;
Engine engine;
}
That a has-a relation.
One criteria you can have to decide whether the classes for Engine, Chasis etc.
needs to be present as an inner class (embedded class) is whether instance of
these classes can be used elsewhere in your application. In such cases the
decision is simple and it is to make these classes exist separately
(not as inner classes).
Even if these classes are not used elsewhere in your application then other
criteria can be testability. With these classes embedded inside and with your
design is it possible to have unit tests that can appropriately test your
code providing a good coverage.
For example say, if you have made an instance variable which references an
Engine object and this variable is being initialized in the Constructor of Car.And
your Engine class has some methods which needs to be tested. Then how can
you add unit tests to check the code in Engine class ? Probably you would
have some methods in Car class which expose the behavior or Engine class allowing
you to write unit tests. Then the question is if there is a need to expose
the behavior of Engine class wouldn't it be better that the Engine class
stands on it own?
Alternatively there might not be a need to explicitly test the methods in
Engine class and unit testing the methods in Car covers the Engine class code
as well. Then it reflects tight integration of Engine class with the Car class
and would mean it can remain as an inner class.
It depends on what it is you're trying to do. Trying to design a 'Car' class (or any other class for that matter) without an idea of the use cases is an exercise in futility.
You will design the classes and their relationships and interactions very differently depending on the use cases you're trying to enable.

Inheritance and interfaces

This is somewhat of a follow-up question to this question.
Suppose I have an inheritance tree as follows:
Car -> Ford -> Mustang -> MustangGT
Is there a benefit to defining interfaces for each of these classes? Example:
ICar -> IFord -> IMustang -> IMustangGT
I can see that maybe other classes (like Chevy) would want to implement Icar or IFord and maybe even IMustang, but probably not IMustangGT because it is so specific. Are the interfaces superfluous in this case?
Also, I would think that any class that would want to implement IFord would definitely want to use its one inheritance by inheriting from Ford so as not to duplicate code. If that is a given, what is the benefit of also implementing IFord?
In my experience, interfaces are best used when you have several classes which each need to respond to the same method or methods so that they can be used interchangeably by other code which will be written against those classes' common interface. The best use of an interface is when the protocol is important but the underlying logic may be different for each class. If you would otherwise be duplicating logic, consider abstract classes or standard class inheritance instead.
And in response to the first part of your question, I would recommend against creating an interface for each of your classes. This would unnecessarily clutter your class structure. If you find you need an interface you can always add it later. Hope this helps!
Adam
I also agree with adamalex's response that interfaces should be shared by classes that should respond to certain methods.
If classes have similar functionality, yet are not directly related to each other in an ancestral relationship, then an interface would be a good way to add that function to the classes without duplicating functionality between the two. (Or have multiple implementations with only subtle differences.)
While we're using a car analogy, a concrete example. Let's say we have the following classes:
Car -> Ford -> Escape -> EscapeHybrid
Car -> Toyota -> Corolla -> CorollaHybrid
Cars have wheels and can Drive() and Steer(). So those methods should exist in the Car class. (Probably the Car class will be an abstract class.)
Going down the line, we get the distinction between Ford and Toyota (probably implemented as difference in the type of emblem on the car, again probably an abstract class.)
Then, finally we have a Escape and Corolla class which are classes that are completely implemented as a car.
Now, how could we make a Hybrid vehicle?
We could have a subclass of Escape that is EscapeHybrid which adds a FordsHybridDrive() method, and a subclass of Corolla that is CorollaHybrid with ToyotasHybridDrive() method. The methods are basically doing the same thing, but yet we have different methods. Yuck. Seems like we can do better than that.
Let's say that a hybrid has a HybridDrive() method. Since we don't want to end up having two different types of hybrids (in a perfect world), so we can make an IHybrid interface which has a HybridDrive() method.
So, if we want to make an EscapeHybrid or CorollaHybrid class, all we have to do is to implement the IHybrid interface.
For a real world example, let's take a look at Java. A class which can do a comparison of an object with another object implements the Comparable interface. As the name implies, the interface should be for a class that is comparable, hence the name "Comparable".
Just as a matter of interest, a car example is used in the Interfaces lesson of the Java Tutorial.
You shouldn't implement any of those interfaces at all.
Class inheritance describes what an object is (eg: it's identity). This is fine, however most of the time what an object is, is far less important than what an object does. This is where interfaces come in.
An interface should describe what an object does), or what it acts like. By this I mean it's behavior, and the set of operations which make sense given that behaviour.
As such, good interface names should usually be of the form IDriveable, IHasWheels, and so on. Sometimes the best way to describe this behaviour is to reference a well-known other object, so you can say "acts like one of these" (eg: IList) but IMHO that form of naming is in the minority.
Given that logic, the scenarios where interface inheritance makes sense are completely and entirely different from the scenarios where object inheritance makes sense - often these scenarios don't relate to eachother at all.
Hope that helps you think through the interfaces you should actually need :-)
I'd say only make an interface for things you need to refer to. You may have some other classes or functions that need to know about a car, but how often will there be something that needs to know about a ford?
Don't build stuff you don't need. If it turns out you need the interfaces, it's a small effort to go back and build them.
Also, on the pedantic side, I hope you're not actually building something that looks like this hierarchy. This is not what inheritance should be used for.
Create it only once that level of functionality becomes necessary.
Re-factoring Code is always on on-going process.
There are tools available that will allow you to extract to interface if necessary.
E.G. http://geekswithblogs.net/JaySmith/archive/2008/02/27/refactor-visual-studio-extract-interface.aspx
Make an ICar and all the rest (Make=Ford, Model=Mustang, and stuff) as members of a class that implements the interface.
You might wanna have your Ford class and for example GM class and both implement ICar in order to use polymorphism if you don't wanna go down the route of checking Make == Whatever, that's up to your style.
Anyway - In my opinion those are attributes of a car not the other way around - you just need one interface because methods are common: Brake, SpeedUp, etc.
Can a Ford do stuff that other cars cannot? I don't think so.
I woudl create the first two levels, ICar and IFord and leave the second level alone until I need an interface at that second level.
Think carefully about how your objects need to interact with each other within your problem domain, and consider if you need to have more than one implementation of a particular abstract concept. Use Interfaces to provide a contract around a concept that other objects interact with.
In your example, I would suggest that Ford is probably a Manufacturer and Mustang is a ModelName Value used by the Manufacturer Ford, therefore you might have something more like:
IVehichle -> CarImpl, MotorbikeImpl - has-a Manufacturer has-many ModelNames
In this answer about the difference between interface and class, I explained that:
interface exposes what a concept is (in term of "what is" valid, at compilation time), and is used for values (MyInterface x = ...)
class exposes what a concept does (actually executed at runtime), and is used for values or for objects (MyClass x or aMyClass.method() )
So if you need to store into a 'Ford' variable (notion of 'value') different sub-classes of Ford, create an IFord. Otherwise, do not bother until you actually need it.
That is one criteria: if it is not met, IFord is probably useless.
If it is met, then the other criteria exposed in the previous answers apply: If a Ford has a richer API than a Car, an IFord is useful for polymorphisms purpose. If not, ICar is enough.
In my view interfaces are a tool to enforce a requirement that a class implement a certain signature, or (as I like to think of it) a certain "Behavior" To me I think if the Capital I at the beginning of my onterface names as a personal pronoun, and I try to name my interfaces so they can be read that way... ICanFly, IKnowHowToPersistMyself IAmDisplayable, etc... So in your example, I would not create an interface to Mirror the complete public signature of any specific class. I would analyze the public signature (the behavior) and then separate the members into smaller logical groups (the smaller the better) like (using your example) IMove, IUseFuel, ICarryPassengers, ISteerable, IAccelerate, IDepreciate, etc... And then apply those interfaces to whatever other classes in my system need them
In general, the best way to think about this (and many questions in OO) is to think about the notion of a contract.
A contract is defined as an agreement between two (or more) parties, that states specific obligations each party must meet; in a program, this is what services a class will provide, and what you have to provide the class in order to get the services. An interface states a contract that any class implementing the interface must satisfy.
With that in mind, though, your question somewhat depends on what language you're using and what you want to do.
After many years of doing OO (like, oh my god, 30 years) I would usually write an interface for every contract, especially in Java, because it makes tests so much easier: if I have an interface for the class, I can build mock objects easily, almost trivially.
Interfaces are intended to be a generic public API, and users will be restricted to using this public API. Unless you intend users to be using the type-specific methods of IMustangGT, you may want to limit the interface hierarchy to ICar and IExpensiveCar.
Only inherit from Interfaces and abstract classes.
If you have a couple of classes wich are almost the same, and you need to implement the majority of methods, use and Interface in combination with buying the other object.
If the Mustang classes are so different then not only create an interface ICar, but also IMustang.
So class Ford and Mustang can inherit from ICar, and Mustang and MustangGT from ICar and IMustang.
If you implement class Ford and a method is the same as Mustang, buy from Mustang:
class Ford{
public function Foo(){
...
Mustang mustang = new Mustang();
return mustang.Foo();
}