Declarations And Access Control
Table of Contents

Interfaces

  • An interface is simply a contract that everyone agrees to. For eg. Car. Every car manufacturer, owner, mechanic and everyone else has agreed to the look and behavior of a Car. But, everyone also agreed that they can customize the car according to their wish. So, Car is an interface - it says you what a Car can have usually. But it doesn't shows you the logic behind the functionality of a Car!
  • An interface tells you what a thing can do but not how it does.
  • An interface is declared using the keyword interface.
  • An interface has to be implemented by a class. Any class from any inheritance tree can implement one or more interfaces.
  • An interface itself can only extend other interfaces but cannot implement atleast one interface.
  • An interface cannot extend or implement a class.
  • Interfaces are purely abstract.
  • Interfaces can be declared inside a package.
  • Interfaces can have either a public or default access level.
  • Interfaces can have fields but they should be constants. Means, the fields should be public, static and final. This is an implicit behavior. Declaring public, static and final is considered as redundant.
  • Interfaces can only have abstract methods that are also public. This is an implicit behavior. Declaring public and abstract is considered as redundant.
  • Interfaces can't be instantiated. So, they don't have constructors.
  • Since the fields declared inside an interface are implicitly final, they must be assigned a value. This assignment should happen in the same line where they are declared.
  • Usually, if a final field/variable is not assigned a value where its declared, the value is assigned inside the constructor or before the constructor completes. But, as said earlier, an interface can't have constructors. So, the final field has to be assigned a value where it is declared.
  • Interface methods cannot be static. Because, interface methods are abstract and must be overridden by the implementing class. But, static methods are not overridden. If you see a static method in a super as well as sub class, it is redeclaration and not overriding. So, a method can never be static and abstract at the same time.
  • Interface methods cannot be final. Because, abstract and final are purely opposite. abstract methods must be overridden. final methods must not be overridden.
  • Interface methods cannot be strictfp, native and synchronized. Because, it is already abstract!
Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-Share Alike 2.5 License.