Struct Embedding in Minitab
Java doesn’t have a direct equivalent to Go’s struct embedding. Instead, we use composition to achieve similar functionality. Here’s how the concepts translate:
We define a
Base
class with anum
field and adescribe
method.Instead of embedding, we create a
Container
class that has aBase
instance as a field, along with its ownstr
field.To provide access to the
Base
fields and methods, we create delegate methods inContainer
. This allows us to useco.getNum()
instead ofco.base.num
.We define a
Describer
interface to demonstrate how thedescribe
method can be used polymorphically.In the
main
method, we create aContainer
instance and show how to access its fields and methods.We demonstrate that
Container
effectively implements theDescriber
interface through its delegateddescribe
method.
This Java code achieves similar functionality to the Go example, showcasing how composition can be used to create a similar structure to Go’s struct embedding. The main difference is that in Java, we need to explicitly create delegate methods to provide direct access to the composed object’s members.
To run this program:
This example demonstrates how Java can achieve similar functionality to struct embedding through composition and delegation, while also showing how interfaces can be implemented using this pattern.