Welcome to the Java Tutorial on Structural Patterns! In this lesson, we'll explore how to compose complex classes by defining simple, reusable classes, and extend the functionality of existing classes without modifying them. 💡
Structural patterns are a type of design pattern that aim to solve problems related to object composition. These patterns organize classes and objects to form larger structures that are easy to maintain, reuse, and extend. 📝
In Java, we'll cover two essential structural patterns: Composition and Inheritance.
Composition is a way of linking objects and classes together, but unlike inheritance, composition does not create an is-a relationship. Instead, it creates a has-a relationship. 📝
Let's create a Car class and an Engine class using Composition.
public class Engine {
private String engineType;
public Engine(String engineType) {
this.engineType = engineType;
}
public void start() {
System.out.println("Engine Started: " + engineType);
}
}
public class Car {
private Engine engine;
private String carName;
public Car(String carName, Engine engine) {
this.carName = carName;
this.engine = engine;
}
public void start() {
engine.start();
System.out.println(carName + " started!");
}
}Let's test our classes:
public class Main {
public static void main(String[] args) {
Engine engine = new Engine("V8");
Car car = new Car("Mustang", engine);
car.start();
}
}Output:
Engine Started: V8
Mustang started!
Here, the Car class has a reference to the Engine class, and it uses the Engine object's start() method to simulate the car starting. This demonstrates the has-a relationship.
Inheritance is a way of creating a new class based on an existing class, inheriting the properties and methods of the existing class. Inheritance creates an is-a relationship between the parent and child classes. 📝
Let's create a Vehicle class and a Car class using Inheritance.
public class Vehicle {
private String name;
public Vehicle(String name) {
this.name = name;
}
public void start() {
System.out.println(name + " started!");
}
}
public class Car extends Vehicle {
public Car() {
super("Car");
}
}Let's test our classes:
public class Main {
public static void main(String[] args) {
Car car = new Car();
car.start();
}
}Output:
Car started!
Here, the Car class inherits the start() method from the Vehicle class, and we don't need to override it since it's applicable to all types of vehicles.
What is the main difference between Composition and Inheritance in Java?
By understanding and applying Structural Patterns, you'll be able to design robust and maintainable object structures in your Java projects. Happy coding! 🚀