Running on Java 21-ea+24-2086 (Preview)
Home of The JavaSpecialists' Newsletter

3.25 Forcing Everyone To Use Static Methods

Juppies 2 by Dr Heinz M. Kabutz

Next we would like to stop someone from constructing the ArrayShuffler class, since they should be calling the static method instead. The first step is to add a constructor and make it private, like this:

  private ArrayShuffler() {}

When we now try to run our application, we find several places where we called shuffle on an object of type ArrayShuffler, rather than on the class. We fix those to instead call the static method.

Note that when we tried running the code again, it now tried to compile the test classes and those also failed. The tests were not compiled together with the main game, since they are a different part of the system.

We again replace the new ArrayShuffer() code with calling the static method on the class with ArrayShuffler.shuffle().

Everything works, so we commit our code.

Comments

When you load these comments, you'll be connected to Disqus. Privacy Statement.

Table of Contents

We hope you enjoyed this tutorial. If you did, you will also enjoy our courses. We suggest you start with Extreme Java - Advanced Java, followed by Extreme Java - Concurrency Performance for Java 8.



About the Author

Heinz Kabutz Java Conference Speaker

Java Champion, author of the Javaspecialists Newsletter, conference speaking regular... About Heinz

Superpack '23

Superpack '23 Our entire Java Specialists Training in one huge bundle more...

Free Java Book

Dynamic Proxies in Java Book
Java Training

We deliver relevant courses, by top Java developers to produce more resourceful and efficient programmers within their organisations.

Java Consulting

We can help make your Java application run faster and trouble-shoot concurrency and performance bugs...

Java Emergency?

If your system is down, we will review it for 15 minutes and give you our findings for just 1 € without any obligation.