Wednesday 31 December 2014

How to Declare Interfaces in Java?

Every class in java exposes an interface which is used by other classes to communicate with exposed class.The class exposed interface includes non private methods,constructors,fields that are optionally used by other class's objects to communicate with exposed class.

Java Formalize this concept by giving reserve word "interface". which is used to give a "type" without implementation .

How to Declare Interface?

interface is declared by writing a reserved word interface followed by valid java identifier name and followed by {} open and close braces

interface Drawable
{
      int RED=2;
      int BLUE=3;
      int BLACK=4;
      int void draw(int color);

}

I declared Drawable interface.You can precede interface with public to make it visible outside of its package.

how to Implement Interface:

Java provides a reserved word  "implements" to implement interface by any class or another interface

for example 

class Shape implements Drawable
{
    // all code goes here
 }

Shape class must override all methods of implemented interface until Shape is not abstract.

Important notes about interface:

  • an interface is abstract by default
  • its fields are public static final by default
  • its methods are public and abstract by default.
  • don't make methods static because interface methods are instance methods.
 


 


No comments:

Post a Comment