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:

  1. We define a Base class similar 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 create delegate methods in Container to access the Base fields and methods. This allows us to use co.getNum() and co.describe() similar to how we used co.num and co.describe() in Go.

  4. Java uses interfaces for polymorphism. We use a Supplier<String> interface to demonstrate similar functionality to the describer interface in Go.

  5. When creating an instance of Container, we explicitly create a Base instance and pass it to the Container 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.