Sure Chris,
I'll provide a simple example to illustrate both inheritance and composition in Java, focusing on a scenario where we have a class representing a basic `Car` and a specialized `SportsCar`. But I’m pretty certain that you don’t need instruction on when to use one versus another.
Sorry, Medium doesn’t provide much code formatting support in the “Reply” editor.
Inheritance Example
Inheritance allows a class to inherit properties and behavior (methods) from another class. Here, `SportsCar` extends `Car`, inheriting its properties and methods. This is a "is-a" relationship.
// Base class
class Car {
public void startEngine() {
System.out.println("Engine started");
}
public void stopEngine() {
System.out.println("Engine stopped");
}
}
// Derived class
class SportsCar extends Car {
public void turboBoost() {
System.out.println("Turbo boost activated");
}
}
public class Main {
public static void main(String[] args) {
SportsCar mySportsCar = new SportsCar();
mySportsCar.startEngine(); // Inherited method
mySportsCar.turboBoost(); // Own method
mySportsCar.stopEngine(); // Inherited method
}
}
```
Composition Example
Composition involves creating classes that contain objects of other classes. This is a "has-a" relationship, where `SportsCar` has a `Car` object.
// Component class
class Engine {
public void start() {
System.out.println("Engine started");
}
public void stop() {
System.out.println("Engine stopped");
}
}
// Another Component
class TurboBooster {
public void activate() {
System.out.println("Turbo boost activated");
}
}
// Composed class
class SportsCar {
private Engine engine;
private TurboBooster turboBooster;
public SportsCar() {
engine = new Engine();
turboBooster = new TurboBooster();
}
public void startEngine() {
engine.start();
}
public void stopEngine() {
engine.stop();
}
public void activateTurbo() {
turboBooster.activate();
}
}
public class Main {
public static void main(String[] args) {
SportsCar mySportsCar = new SportsCar();
mySportsCar.startEngine(); // Composition
mySportsCar.activateTurbo(); // Composition
mySportsCar.stopEngine(); // Composition
}
}
```
In the inheritance example, `SportsCar` is a `Car` and directly inherits its behavior. In the composition example, `SportsCar` is composed of `Engine` and `TurboBooster` objects, demonstrating a more flexible design that allows you to easily replace components without affecting the `SportsCar` class. This is beneficial for scenarios where behaviors can vary independently or are expected to change over time.