Struct Embedding in Fortress
Java doesn’t have direct support for struct embedding like in Go. Instead, we use composition and delegation to achieve similar functionality. Here’s how the concepts are translated:
The
Base
class is defined similarly to thebase
struct in Go.Instead of embedding, the
Container
class has aBase
instance as a private field.To provide access to the
Base
fields and methods, we create delegate methods inContainer
. This allows us to accessnum
anddescribe()
through theContainer
instance.The
Describer
interface is defined similarly to Go.In the
main
method, we create aContainer
instance and demonstrate how to access its properties and methods.We show that
Container
effectively implements theDescriber
interface through method reference (co::describe
).
When creating instances, we need to explicitly create both the Base
and Container
objects:
We can access the base’s fields and methods through the delegate methods:
The Describer
interface is implemented implicitly through the delegated describe()
method:
This Java code demonstrates how to achieve similar functionality to Go’s struct embedding using composition and delegation. While not as seamless as Go’s embedding, it provides a way to compose types and share behavior in an object-oriented manner.