Interface in java with example


Interface

Interface provides a standards that to be implemented in a related class.

Implementing an interface allows a class to become more formal about the behavior it promises to provide. Interfaces form a contract between the class and the outside world, and this contract is enforced at build time by the compiler. If your class claims to implement an interface, all methods defined by that interface must appear in its source code before the class will successfully compile.

 

Rules:

                By default all methods in interface are public and abstract. (No need to mention it explicitly)

                Variables declared in interface are by default public, static and final.

                Implemented class guaranty that all methods declared in the interfaces are defined unless the                 class is not abstract.

                Class can implement any number of interfaces

                Interface can extend any number of interfaces

 

Example

interface User
{
	float PI=3.14f; // becomes constant, by default it uses public static final keyword

	void add(); // declaration, by default it uses abstract and public

	void update();

	void delete();
}
class Manager implements User
{
	public void add() // public keyword should be explicitly given in class
	{
		System.out.println(?adding manager?);
	}

	public void update()
	{
		System.out.println(?updating  manager?);
	}

	public void delete()
	{
		System.out.println(?deleting manager?);
	}
} 




Related Post

Comments


©candidjava.com