Issue
I'm studying object-oriented programming and it's confusing.
There are two classes which are Driver and Vehicle. Car and MotorBike is inherited by Vehicle class.
public class Driver{
void drive(Vehicle vehicle){
vehicle.moveForward();
vehicle.moveBackward();
}
}
// the problem code
public static void main(String[] args){
Vehicle car = new Car(); // tight coupling
Vehicle motorBike = new MotorBike(); // tight coupling
Driver driver = new Driver();
driver.drive(car);
driver.drive(motorBike);
}
The instances created with new Car() and new MotorBike() exhibit tight coupling.
Therefore, I modified the code to reduce tight coupling by employing dependency injection. However, I'm not sure it's right or not. It seems like that tight coupling is still exist on new Car and new MotorBike instances.
// the code I wrote
public static void main(String[] args){
Driver driver = new Driver();
driver.drive(new Car());
driver.drive(new MotorBike());
}
Please correct the code I wrote. Thank you!
Solution
Look at this code. You should accept the car or bike object through constructor to decouple the code.
public class Driver {
private final Vehicle vehicle;
public Driver(Vehicle vehicle) {
this.vehicle = vehicle;
}
void drive() {
vehicle.moveForward();
vehicle.moveBackward();
}
}
Then in you main mehthod , create the object of car or bike and pass to driver constructor. like this.
public static void main(String[] args) {
Driver driver = new Driver(new Car());
driver.drive();
driver = new Driver(new MotorBike());
driver.drive();
}
Answered By - kevalsing
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.