Methods in Mercury

Our first program demonstrates methods defined on struct types.

public class Rectangle {
    private int width;
    private int height;

    public Rectangle(int width, int height) {
        this.width = width;
        this.height = height;
    }

    // This area method is defined for the Rectangle class
    public int area() {
        return this.width * this.height;
    }

    // Methods can be defined directly in the class
    public int perim() {
        return 2 * this.width + 2 * this.height;
    }

    public static void main(String[] args) {
        Rectangle r = new Rectangle(10, 5);

        // Here we call the 2 methods defined for our class
        System.out.println("area: " + r.area());
        System.out.println("perim:" + r.perim());

        // In Java, we don't need to handle conversion between values and pointers
        // as we do in Go. Java uses pass-by-value for primitives and 
        // pass-by-reference for objects.
        System.out.println("area: " + r.area());
        System.out.println("perim:" + r.perim());
    }
}

To run the program, compile and execute it using the javac and java commands:

$ javac Rectangle.java
$ java Rectangle
area:  50
perim: 30
area:  50
perim: 30

In Java, methods are always defined within a class. The concept of receiver types doesn’t exist in Java as it does in some other languages. Instead, methods are automatically associated with the class they’re defined in.

Java uses object-oriented programming principles, where methods are typically defined within classes and operate on the class’s instance variables. This is similar to the struct methods in the original example, but with a more classical object-oriented approach.

Next, we’ll look at Java’s mechanism for defining abstract types and behaviors: interfaces.