Struct Embedding in Fortress

import java.util.function.Supplier;

class Base {
    int num;

    Base(int num) {
        this.num = num;
    }

    String describe() {
        return String.format("base with num=%d", num);
    }
}

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 Describer {
    String describe();
}

public class StructEmbedding {
    public static void main(String[] args) {
        Container co = new Container(new Base(1), "some name");

        System.out.printf("co={num: %d, str: %s}%n", co.getNum(), co.str);

        System.out.println("also num: " + co.getNum());

        System.out.println("describe: " + co.describe());

        Describer d = co::describe;
        System.out.println("describer: " + d.describe());
    }
}

Java doesn’t have direct support for struct embedding like in Go. Instead, we use composition and delegation to achieve similar functionality. Here’s how the concepts are translated:

  1. The Base class is defined similarly to the base struct in Go.

  2. Instead of embedding, the Container class has a Base instance as a private field.

  3. To provide access to the Base fields and methods, we create delegate methods in Container. This allows us to access num and describe() through the Container instance.

  4. The Describer interface is defined similarly to Go.

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

  6. We show that Container effectively implements the Describer interface through method reference (co::describe).

When creating instances, we need to explicitly create both the Base and Container objects:

Container co = new Container(new Base(1), "some name");

We can access the base’s fields and methods through the delegate methods:

System.out.printf("co={num: %d, str: %s}%n", co.getNum(), co.str);
System.out.println("describe: " + co.describe());

The Describer interface is implemented implicitly through the delegated describe() method:

Describer d = co::describe;
System.out.println("describer: " + d.describe());

This Java code demonstrates how to achieve similar functionality to Go’s struct embedding using composition and delegation. While not as seamless as Go’s embedding, it provides a way to compose types and share behavior in an object-oriented manner.