Interface

What is Interface?

Interface is similar to java class but contains only abstract methods. An interface also can contain constants, default methods, static methods, and nested types. Method bodies exist only for default methods and static methods.

Following are interface properties:

  • Interface can not be instantiated like abstract class
  • Interface contains abstract methods without body
  • Interface can also contain default and static methods with body
  • Interface does not contain constructor like java class
  • It can implement multiple interfaces in one java class
package com.itwhistle.oops;

public interface ITWhistleInterface {

	// abstract method
	public int addThree(int x, int y, int z);

	// abstract method
	public int addFour(int a, int b, int c, int d);

	// default method with method body
	default int addTwo(int a, int b) {

		return a + b;
	}

	// static method with method body
	public static int subTwo(int a, int b) {

		return a - b;
	}
}
package com.itwhistle.oops;

public class ITWhistleImpl implements ITWhistleInterface {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		ITWhistleInterface obj = new ITWhistleImpl();

		// calling Interface default method
		System.out.println("Adding two numbers " + obj.addTwo(5, 5));
		// calling Impl class methods addThree and addFour
		System.out.println("Adding three numbers " + obj.addThree(10, 20, 30));
		System.out.println("Adding four numbers " + obj.addFour(5, 5, 5, 5));
		// calling subTwo method from Interface using Interface name in static way
		System.out.println("Subtracting two numbers " + ITWhistleInterface.subTwo(10, 5));
	}

	@Override
	public int addThree(int x, int y, int z) {
		// TODO Auto-generated method stub
		return x + y + z;
	}

	@Override
	public int addFour(int a, int b, int c, int d) {
		// TODO Auto-generated method stub
		return a + b + c + d;
	}

}