Interfaces

In object-oriented programming, it is sometimes helpful to define what a class must do but not how it will do it. You have already seen an example of this: the abstract method. An abstract method defines the signature for a method but provides no implementation. A subclass must provide its own implementation of each abstract method defined by its superclass. Thus, an abstract method specifies the interface to the method but not the implementation.While abstract classes and methods are useful, it is possible to take this concept a step further. In Java, you can fully separate a class’s interface from its implementation by using the keyword interface.

Defining an Interface

interface Firstinter {
	void method1();
	void method2();
}

class InterfaceTest implements Firstinter {
	public void method1() { // conpulsory to override all the methods
		System.out.println("Inside Method1");

	}

	public void method2() {
		System.out.println("Inside Method2");
	}
}

public class InterfaceExample {
	public static void main(String[] args) {
		InterfaceTest obj1 = new InterfaceTest();
		obj1.method1();
		obj1.method2();
	}
}

Variables in Interfaces

Example will be as follows :

interface sample {
	int on = 1;
	int off = 0;
}

class abc implements sample {
	void methodUnderabc() {
		System.out.println(on);
		System.out.println(off);
	}
}

public class VariablesInInterfaces {
	public static void main(String[] args) {
		abc ab = new abc();
		ab.methodUnderabc();
	}
}