Methods in Minitab

Java supports methods defined on class 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 within the Rectangle class
    public int area() {
        return this.width * this.height;
    }

    // Methods can be defined for instance methods in Java
    public int perimeter() {
        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("perimeter: " + r.perimeter());

        // In Java, all non-primitive variables are references,
        // so there's no need for explicit pointer handling
        Rectangle rp = r;
        System.out.println("area: " + rp.area());
        System.out.println("perimeter: " + rp.perimeter());
    }
}

To run the program:

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

In Java, methods are always associated with classes. There’s no distinction between value and pointer receivers as in some other languages. All non-primitive variables in Java are references to objects.

Java uses object-oriented programming principles, where methods are defined within classes and operate on the object’s state. This is similar to the concept of methods in other languages, but with its own specific syntax and rules.

Next, we’ll look at Java’s mechanism for defining contracts for classes: interfaces.