Struct Embedding in CLIPS
import java.util.function.Supplier;
class Base {
private int num;
public Base(int num) {
this.num = num;
}
public String describe() {
return String.format("base with num=%d", num);
}
public int getNum() {
return 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;
}
// Delegating method
public String describe() {
return base.describe();
}
public int getNum() {
return base.getNum();
}
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");
// Accessing the base's fields through Container's methods
System.out.printf("co={num: %d, str: %s}%n", co.getNum(), co.getStr());
// We can still access the base object if needed
System.out.println("also num: " + co.getNum());
// Calling the delegated method
System.out.println("describe: " + co.describe());
// Using a functional interface for demonstration
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 to achieve similar functionality. Here’s how the concepts translate:
We define a
Baseclass that corresponds to thebasestruct in Go.Instead of embedding, we create a
Containerclass that has aBaseinstance as a field.We implement methods in
Containerthat delegate to theBaseinstance. This allows us to accessBasemethods throughContainer, similar to how embedding works in Go.In the
mainmethod, we create aContainerinstance and demonstrate how to access its properties and methods.Java doesn’t have implicit interface implementation through composition. Instead, we use a functional interface (
Supplier) to demonstrate a similar concept.
When you run this program, you’ll see output similar to the Go version:
co={num: 1, str: some name}
also num: 1
describe: base with num=1
describer: base with num=1This example shows how to achieve functionality similar to Go’s struct embedding in Java using composition and delegation. While the syntax and approach are different, the end result is quite similar in terms of behavior and structure.