Suresh Rohan's Blog

This blog is all about Java, J2EE,Spring, Angular, React JS, NoSQL, Microservices, DevOps, BigData, Tutorials, Tips, Best practice, Interview questions, Views, News, Articles, Techniques, Code Samples, Reference Application and much more

Monday, October 26, 2015

Interfaces in Java


In general, an interface refers to a common boundary or interconnection between two entities.

In Java, an interface is a set of abstract methods that defines a protocol. Classes that implement an interface must implement the methods specified in the interface. 

A class combines the state and the behavior of a real object, whereas an interface specifies the behavior of an abstract entity.

For example, java.util defines the Iterable interface as follows:


public interface Iterator<E> {
boolean hasNext();
E next();
void remove();
}

Points to Remember

  • An interface cannot be instantiated.
  • An interface can extend another interface. Use the extends.
  • Interfaces cannot contain instance variables. If you declare a data member in an interface, it should be initialized, and all such data members are implicitly treated as “public static final” members.
  • An interface cannot declare static methods. It can only declare instance methods.
  • You cannot declare members as protected or private. Only public access is allowed for members of an interface.
  • All methods declared in an interface are implicitly considered to be abstract. If you want, you can explicitly use the abstract qualifier for the method.
  • You can only declare (and not define) methods in an interface.
  • An interface can be declared with empty body (i.e., an interface without any members. Such interfaces are known as tagging interfaces (or marker interfaces). Such interfaces are useful for defining a common parent, so that runtime polymorphism can be used. For example, java.util defines the interface EventListner without a body.
  • An interface can be declared within another interface or class; such interfaces are known as nested interfaces.
  • Unlike top-level interfaces that can have only public or default access, a nested interface can be declared as public, protected, or private.




No comments:

Post a Comment