Struct Embedding in Fortress
import java.util.function.Supplier;
class Base {
int num;
Base(int num) {
this.num = num;
}
String describe() {
return String.format("base with num=%d", num);
}
}
class Container {
private Base base;
String str;
Container(Base base, String str) {
this.base = base;
this.str = str;
}
// Delegate method to access base's num
int getNum() {
return base.num;
}
// Delegate method to access base's describe
String describe() {
return base.describe();
}
}
interface Describer {
String describe();
}
public class StructEmbedding {
public static void main(String[] args) {
Container co = new Container(new Base(1), "some name");
System.out.printf("co={num: %d, str: %s}%n", co.getNum(), co.str);
System.out.println("also num: " + co.getNum());
System.out.println("describe: " + co.describe());
Describer d = co::describe;
System.out.println("describer: " + d.describe());
}
}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
Baseclass is defined similarly to thebasestruct in Go.Instead of embedding, the
Containerclass has aBaseinstance as a private field.To provide access to the
Basefields and methods, we create delegate methods inContainer. This allows us to accessnumanddescribe()through theContainerinstance.The
Describerinterface is defined similarly to Go.In the
mainmethod, we create aContainerinstance and demonstrate how to access its properties and methods.We show that
Containereffectively implements theDescriberinterface through method reference (co::describe).
When creating instances, we need to explicitly create both the Base and Container objects:
Container co = new Container(new Base(1), "some name");We can access the base’s fields and methods through the delegate methods:
System.out.printf("co={num: %d, str: %s}%n", co.getNum(), co.str);
System.out.println("describe: " + co.describe());The Describer interface is implemented implicitly through the delegated describe() method:
Describer d = co::describe;
System.out.println("describer: " + d.describe());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.