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.



Java Garage
Java Garage
ISBN: 0321246233
EAN: 2147483647
Year: 2006
Pages: 228
Authors: Eben Hewitt

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net