Structs in Java

Go’s structs are typed collections of fields. They’re useful for grouping data together to form records.

public class Person {
    String name;
    int age;
    
    Person(String name) {
        this.name = name;
        this.age = 42;
    }

    public static void main(String[] args) {
        System.out.println(new Person("Bob").toString());
        System.out.println(new Person("Alice", 30).toString());
        System.out.println(new Person("Fred").toString(true));
        System.out.println(new Person("Jon").toString(true));
        System.out.println(new Person("Sean", 50).getName());
        
        Person p = new Person("Sean", 50);
        System.out.println(p.getAge());
        p.setAge(51);
        System.out.println(p.getAge());
        
        class Dog {
            String name;
            boolean isGood;

            Dog(String name, boolean isGood) {
                this.name = name;
                this.isGood = isGood;
            }
            
            @Override
            public String toString() {
                return String.format("%s %b", name, isGood);
            }
        }
        
        Dog dog = new Dog("Rex", true);
        System.out.println(dog.toString());
    }
    
    Person(String name, int age) {
        this.name = name;
        this.age = age;
    }
    
    public Person(String name, boolean isPointer) {
        if (isPointer) {
            this.name = name;
            this.age = 42;
        }
    }

    public int getAge() {
        return this.age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public String getName() {
        return this.name;
    }
    
    @Override
    public String toString() {
        return String.format("%s %d", name, age);
    }
}

To run the program, compile the code into a .class file and then use java to execute it.

$ javac Person.java
$ java Person
Bob 42
Alice 30
Fred 42
Jon 42
Sean
50
51
Rex true

Now that we can run and build basic Java programs, let’s learn more about the language.