Struct Embedding in Squirrel
import java.util.function.Supplier;
class Base {
int num;
public Base(int num) {
this.num = num;
}
public String describe() {
return String.format("base with num=%d", num);
}
}
// In Java, we use composition instead of embedding
class Container {
private Base base;
private String str;
public Container(Base base, String str) {
this.base = base;
this.str = str;
}
// Delegate method to access base's num
public int getNum() {
return base.num;
}
// Delegate method to access base's describe
public String describe() {
return base.describe();
}
public String getStr() {
return str;
}
}
public class StructComposition {
public static void main(String[] args) {
// Creating an instance of Container
Container co = new Container(new Base(1), "some name");
// We can access the base's fields through the delegated method
System.out.printf("co={num: %d, str: %s}%n", co.getNum(), co.getStr());
// We can also access the base's method through the delegated method
System.out.println("describe: " + co.describe());
// In Java, we use interfaces for similar functionality
Supplier<String> describer = co::describe;
System.out.println("describer: " + describer.get());
}
}
Java doesn’t have a direct equivalent to Go’s struct embedding. Instead, we use composition and delegate methods to achieve similar functionality. Here’s how the concepts translate:
We define a
Base
class similar to thebase
struct in Go.Instead of embedding, we create a
Container
class that has aBase
instance as a field.We create delegate methods in
Container
to access theBase
fields and methods. This allows us to useco.getNum()
andco.describe()
similar to how we usedco.num
andco.describe()
in Go.Java uses interfaces for polymorphism. We use a
Supplier<String>
interface to demonstrate similar functionality to thedescriber
interface in Go.When creating an instance of
Container
, we explicitly create aBase
instance and pass it to theContainer
constructor.
To run this program:
$ javac StructComposition.java
$ java StructComposition
co={num: 1, str: some name}
describe: base with num=1
describer: base with num=1
This example demonstrates how to achieve similar functionality to Go’s struct embedding in Java using composition and delegation. While the syntax and approach are different, the core concept of reusing and extending functionality is preserved.