Aggregation: hidind the reference
Hi
I want to have methods of aggregated objects accessible, but the reference to the aggregated object not changable externally. Is there any way to do that?
To illustrate the problem here's some example code:
Code:
class Test {
public static void main(String[] args) {
Car car = new Car(new Diesel()); //creates the aggregated object
car.engine = new Otto(); // this must not be allowed!!
car.installEngine(new Otto()); //this should be used instead
car.engine.switchOff(); //and this should work, too!!
}
}
//some more information...
interface Engine { public void switchOff(); }
class Otto implements Engine { .. }
class Diesel implements Engine { .. }
class Car {
protected Engine engine; // The car might have an engine.
Car(Engine e) {engine = e; return;}; // Constructor sets enginetype
protected void installEngine(Engine e){// This method should be used to change the engine
engine.switchOff();
engine = e;
return;
}
}
Thank's in advance
Chris