Monday, March 23, 2015

Interface class

Java includes a concept called interfaces. A Java interface is a bit like a class, except a Java interface can only contain method signatures and fields. An Java interface cannot contain an implementation of the methods, only the signature (name, parameters and exceptions) of the method.

public interface MyInterface {

    public String hello = "Hello";

    public void sayHello();
}
As you can see, an interface is declared using the Java interface keyword. Just like with classes, a Java interface can be declared public or package scope (no access modifier).
The interface example above contains one variable and one method. The variable can be accessed directly from the interface, like this:
System.out.println(MyInterface.hello);
As you can see, accessing a variable from an interface is very similar to accessing a static variable in a class.
The method, however, needs to be implemented by some class before you can access it. 

No comments:

Post a Comment