Struct Embedding in Minitab

public class StructEmbedding {
    static class Base {
        int num;

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

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

    // In Java, we use composition instead of embedding
    static 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 for describing
    interface Describer {
        String describe();
    }

    public static void main(String[] args) {
        // Create a Container instance
        Container co = new Container(new Base(1), "some name");

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

        // Access base's num through the Container
        System.out.println("also num: " + co.getNum());

        // Call the describe method
        System.out.println("describe: " + co.describe());

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

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 with a num field and a describe method.

  2. Instead of embedding, we create a Container class that has a Base instance as a field, along with its own str field.

  3. To provide access to the Base fields and methods, we create delegate methods in Container. This allows us to use co.getNum() instead of co.base.num.

  4. We define a Describer interface to demonstrate how the describe method can be used polymorphically.

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

  6. We demonstrate that Container effectively implements the Describer interface through its delegated describe method.

This Java code achieves similar functionality to the Go example, showcasing how composition can be used to create a similar structure to Go’s struct embedding. The main difference is that in Java, we need to explicitly create delegate methods to provide direct access to the composed object’s members.

To run this program:

$ javac StructEmbedding.java
$ java StructEmbedding
co={num: 1, str: some name}
also num: 1
describe: base with num=1
describer: base with num=1

This example demonstrates how Java can achieve similar functionality to struct embedding through composition and delegation, while also showing how interfaces can be implemented using this pattern.