Java supports composition of classes, which is similar to struct embedding in other languages. This allows for a more seamless composition of types.
In Java, we use composition to achieve a similar effect to struct embedding. The Container class contains an instance of Base and delegates certain methods to it.
When creating objects with composition, we initialize the composed class explicitly in the constructor.
We can access the base’s fields through delegated methods in Container, such as co.getNum().
Since Container composes Base, we can delegate the methods of Base to become methods of Container. Here we invoke a method that was delegated from Base directly on co.
Composition can be used to implement interfaces. Here we see that a Container now implements the Describer interface because it delegates to Base.
To run the program:
This example demonstrates how Java uses composition to achieve a similar effect to struct embedding, allowing for flexible and reusable code structures.