Monday, May 26, 2025

The static modifier

 Some methods are declared “static,” and others aren’t. One that absolutely must be static is main. I know I have said this before, but it is so important it bears repeating: for a Java program to be executable, there must exist, somewhere in the file whose class name matches the file name, a method which is declared public, static, returning void, named main, with one and only one parameter which is an array of Strings.

When a variable is declared static, then it means that value holds for every instance of the class.

Consider a Circle class:
public class Circle {

    public static final double PI = 3.14159;

    private double radius;

    public Circle(double radius) {

        this.radius = radius;

    }

    public double getArea() {

        return PI * radius * radius;

    }

    public double getCircumference() {

        return 2 * PI * radius;

    }
    public double getRadius() {

        return radius;

    }

    public void setRadius(double radius) {

        this.radius = radius;

    }

}

The radius is a fundamental attribute of a circle, not all circles. The radius of a circle depends on which circle you are talking about, so that variable is tied to the particular Circle object in question. You might create one where the radius is 5, and your friend might create one where the radius is 472324. However, for you, your friend, and everyone else literally ever, there is one value of pi, which is unchanging and fundamental to the idea of Circles themselves, not any particular Circle. Since pi’s value doesn’t change from Circle to Circle, it doesn’t belong to one particular Circle, but to the whole class, and is therefore declared static.

When a method is static, you don’t need to create a new instance of its class (for example, Dog myDog = new Dog();
myDog.woof();

in order to use it

Here we are assuming that “woof()” is not static, however it is implemented.)

You can use a static method without creating an instance of the class.

If we knew that woof() was static, then we could instead write something like
Dog.woof();

Classes being declared static can happen (and they are very useful), but those are for much more advanced topics which we will cover much later. For now, it is only important that you know that variables, methods, and classes can be declared static.


No comments:

Post a Comment

Switch

 Other than if/if-else/if-else if-else and the ternary operator, there is yet another common and important conditional expression in Java th...