How to Write an Interface

The Java API is full of terrific interface definitions. One commonly used interface is java.lang.Runnable, which can be implemented to create a thread. To write an interface, you can look at the many good examples in the Java API.

When writing your own, you just use the keyword interface instead of class, and then don't include the method implementations. Like this:

public interface MyInterface {
      public void someMethod(long someParam);
}

As you can see, you just use the interface keyword in place of class. And then you substitute a semi-colon for the curly braces holding the method implementation. That's all you have to do in a nutshell. In the following sections, we'll see the many twisting, cavernous corridors that lurk beneath the deceptively simple interface.

After you have an interface, you implement it. That means you declare a class that implements the interface, and then write the implementation for each method in the interface. And the method signatures must match exactly. Like this:

public MyClass implements MyInterface {
   //since I said "implements MyInterface",
   //I must include this method, or
   //this class won't compile
   public void someMethod(long someParam) {
       //this is my implementation.
   }
}

You can add methods and other stuff to your implementing class if you want to.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.134.77.195