Java:Tutorials:Interfaces

From GPWiki
Jump to: navigation, search

Interfaces In Java

What They Are

One of Java's main selling points is that it was built with OOP in mind. However, to avoid confusion, Java doesn't include multiple inheritance. So they created interfaces. Interfaces are implemented by classes with the 'implements' keyword. For example:

public class Main implements AInterface {

An interface defines methods that a class that implements it must declare, but leaves it up to the class to decide what to put in the method. Just like abstract classes, interfaces can't be instaited. Classes can implement many interfaces, and interfaces can extends multiple interfaces. A typical interface looks like this:

public interface Moveable {

 public void move();

}

Remember, interfaces don't say what a method does. This interface just makes the class have a method called move. The class would look something like this:

public class Thingy implements Moveable {

 //x and y positions of thingy
 private int xpos;
 private int ypos;
 public void move() {
   xpos++;
 }
 public void paint(Graphics g) {
   //drawing method
 }

}

What they are used for

You might be wondering why one would use interfaces. There are several reasons, but here is an example. Let us return to our class Thingy. You want all Thingies to be undead, talking, walking, flying trees. If you were to use abstract classes, this would be almost impossible, because of multiple inheritance. If you used abstract classes you would also most likely destroy relationships between classes. If you were to use interfaces, however, it would be much easier, because class Thingy could implement the interfaces Undead, Walking, Flying, and Talking. Look at this for example:

 public class Thingy implements Undead, Walking, Talking, Flying {
   
   //from interface Walk
   public void walk() {
     //code here
   }
   
   //from interface Fly
   public void fly() {
     //code here
   }
   //from interface Talk
   public void talk() {
      //code here
   }

   //from interface Undead
   public void rejuvinate() {
      //code here
   }
 }

Now you don't ruin the relationships between classes, so your game engine can easily see which classes are able to talk or fly.