Game Development Reference
In-Depth Information
The Java Interface: Defining Rules for Implementing
Your Class
Before we look at the List<E> Java interface, let's take a look at what Java interfaces
do in general, as we did not have enough pages to cover all of the Java programming
language back in Chapter 3 . So I am going to cover some of the more advanced Java
topics as we need to learn them during the topic. A good example of this is lambda ex-
pressions in Chapter 9 and Java interfaces here in Chapter 10 . The reason for using a
Java interface is to make sure that other programmers who are going to use your code
implement it correctly; that is, include everything necessary for the code to work prop-
erly.
Essentially, all an interface specifies is the group of related methods that is needed
for another developer to implement your class. These are specified with “empty meth-
od” code bodies. If you wanted to have other developers use the Hero class, for in-
stance, you would specify a Hero interface. This would be done using the following
Java code:
public interface Hero {
public void update ();
public boolean collide (Actor actor);
}
As you can see, this is similar to what we did with the .update() method in the Act-
or superclass, as there is no {code body} specified as there usually is in a method.
Thus, in a sense, a Java interface is also used in an abstract fashion to define what
needs to be included in a class that “implements” the Java interface. As you probably
have guessed, you would thus use the Java implements keyword in your class declara-
tion to implement a Java interface.
So, if you had defined a Hero interface, and wanted to implement it in one of your
classes, in which case the Java compiler would watch over the code and make sure that
you are implementing the necessary method structures, the class definition line of code
and the methods inside the body of the class would look something like the following:
public class SuperHero implements Hero {
protected boolean flagVariable1, flagVariable2;
public void update () {
// Java statements to process on each update
Search WWH ::




Custom Search