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:

  1. We define a Base class that corresponds to the base struct in Go.

  2. Instead of embedding, we create a Container class that has a Base instance as a field.

  3. We implement methods in Container that delegate to the Base instance. This allows us to access Base methods through Container, similar to how embedding works in Go.

  4. In the main method, we create a Container instance and demonstrate how to access its properties and methods.

  5. 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=1

This 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.