Kotlin
Java

Static
Java

Created By: Geoffrey Challen
/ Updated: 2021-09-19

As we continue, we begin by describing a new design keyword: static. But first, let's introduce one new piece of object syntax...

this

this is a keyword in Java that you can use in your instance methods. It always refers to the current instance that is executing the method.

So this:

is equivalent to this:

The example above is one use of this. However, we'll usually just go the first route, and choose parameter names that don't conflict with our instance variable names. This helps avoid mistakes. checkstyle will help you with this, complaining (as it does above) that your parameter "hides a field".

However, there is one place where we will use this. Let's go through it together:

Discuss the use of this in constructor overloading.

static Methods

The object methods we have been writing so far are known as instance methods:

Even though they share the same implementation, you can think of each Person as having its own getName method that can access its instance variables, in this case name.

However, Java also allows us to create methods that are attached to the class, not to the instance. To do that, we use a new keyword: static. Let's see how that works:

Show an example of a static method: maybe one that prints a greeting giving a string. So how you can call it from the Person or on an instance.

static v. Instance

static class methods cannot access instance variables. Let's look at why, and the differences between class and instance methods:

Distinguish between class and instance methods.

Uses for Static Methods

static class methods are not uncommon. Particularly when you have methods that don't need an instance to function properly. Let's look at one example of a class that consists almost entirely of static methods, Math:

Discuss the Math library.

static Fields

You can also use the static keyword on fields. One common use for this is to establish constants to make our code more readable and less error-prone.

To do this, we combine static with a keyword that we haven't seen before, final. final creates a variable that cannot be changed after it has been set. We can combine static and final to create a symbolic constant. Let's look at how:

Discuss using static final fields to create constants to make your code more readable.

Non-Final static Fields

Can you create modifiable—that is, non-finalstatic fields? Yes. However. This is extremely rare, and very easy to get wrong. We won't test you on it, but view this walkthrough to see how this works:

Demonstrate how to use a modifiable static field to count the number of Course instances. Warn againt this, since it is hard to get right.

Show how to complete the homework problem above. Feel free to cover multiple approaches!

Solution Walkthrough

Show how to complete the homework problem above. Feel free to cover multiple approaches!

Solution Walkthrough