We now want to change the WordLibrary
from an abstract class to an interface.
Prior to Java 8, interfaces could not have any methods with actual code
bodies. The reason is that it is possible for a class to implement several
interfaces. If more than one has a method with the same name and parameter
types, which one should be used? We call this multiple inheritance, and it
caused issues in C++. The good news is that Java 8 allows us to use method
bodies in interfaces. The bad news is that you might not get a chance to code
Java 8 in the "real world" for a while still. Even in the year 2020, where
Java 14 was already around, some companies were still using Java 6. We might find
companies still coding in Java 1.4. Or we might get really unlucky and get
stranded at an organization coding in Java 1.1. That's life. Don't be shocked.
Even though we have some beautiful features in modern Java, it takes effort to
move to the newer versions and sometimes organizations find it more trouble
than worth to upgrade. They fall further and further behind and when they do
eventually change, it is a painful process.
In this course we are using at least Java 14, and right now Java 17 has already been released. By all means use Java 17 if you like.
Let's do the change:
interface
instead of abstract class
.
public abstract
,
so let's take away those redundant modifiers.
isCorrect()
method to have modifier
default
instead of
public
. The method is automatically
public
if written inside an interface.
If we want it to have a method body, we have to add the
default
modifier.
Note: Since Java 9 we can also have private methods declared inside
interfaces, although up to now I have never needed that.
StaticWordLibrary
and
ShuffledWordLibrary
to say
implements WordLibrary
instead of
extends WordLibrary
. When a class
implements an interface, we use implements
, and
when it extends a class we use extends
. When an interface extends another
interface we also use extends
.
We run our game, which also runs our tests.
Whenever possible, we should use interfaces instead of abstract classes. One
thing that an abstract class can do, which an interface cannot do, is to
contain fields. If we declare a field inside an interface it will automatically be
public static final
, just like a constant. An abstract class can contain
data just like a normal class.
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.
We deliver relevant courses, by top Java developers to produce more resourceful and efficient programmers within their organisations.
We can help make your Java application run faster and trouble-shoot concurrency and performance bugs...