Struct Embedding in Minitab
public class StructEmbedding {
static class Base {
int num;
Base(int num) {
this.num = num;
}
String describe() {
return String.format("base with num=%d", num);
}
}
// In Java, we use composition instead of embedding
static 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 for describing
interface Describer {
String describe();
}
public static void main(String[] args) {
// Create a Container instance
Container co = new Container(new Base(1), "some name");
// Access fields
System.out.printf("co={num: %d, str: %s}%n", co.getNum(), co.str);
// Access base's num through the Container
System.out.println("also num: " + co.getNum());
// Call the describe method
System.out.println("describe: " + co.describe());
// Demonstrate interface implementation
Describer d = co::describe;
System.out.println("describer: " + d.describe());
}
}
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:
$ javac StructEmbedding.java
$ java StructEmbedding
co={num: 1, str: some name}
also num: 1
describe: base with num=1
describer: base with num=1
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.