Methods in Java

Java supports methods defined on class types.

public class Rectangle {
    private int width, 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 for either instance or static types
    // Here's an example of an instance method
    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());

        // Java automatically handles method calls on objects
        // There's no need for explicit pointer dereferencing
        System.out.println("area: " + r.area());
        System.out.println("perimeter: " + r.perimeter());
    }
}

To run the program:

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

In Java, all methods are associated with classes, and there’s no distinction between pointer and value receivers as in some other languages. Methods are always called on objects (instances of classes) or, in the case of static methods, on the class itself.

Java uses object references instead of pointers. When you create an object with new, you’re working with a reference to that object. There’s no need to use & to get a reference or * to dereference.

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