Learn all about methods in interface in java with very simple code example and explanation.

Interface in java contains only declaration of methods as shown below in interface example. All the methods in an interface are by default public and abstract and they cannot have definition or implementation.

interface A {
	void f1();
	void f2();
	void f3();
}

Even though, if you don’t write public and abstract before methods, the compiler will by default treat them as public and abstract. In above example, we have not declare methods f1(), f2() and f3() public and abstract.

So for, you understand that methods in an interface do not have implementation. Meaning, it does not have body.

Now, you might be wondering, what is the use of unimplemented methods?

Answer is, all methods of interface are implemented by the classes who inherit and implement the interface.

FOCUS:

  • All methods of an interface must be overridden and implemented by the classes who implement the interface.
  • Abstract keyword before methods forces the sub classes / derived classes in inheritance relationship in java to implement interface methods. If you miss any method implementation in subclass, the compiler will throw an error.

Lets understand how we can write methods in an interface in java and how to inherit and implement those abstract methods by classes.

Example of Interface methods in Java

In below java code example, there is an interface “Screen” having two methods unimplemented methods i.e. LED() and LCD. There is a class TV that will implement the interface Screen. TV class will override and implement both abstract methods.

/*
 * Interface methods java example
 */

interface Screen {
	void LED();

	void LCD();
}

// TV class will override and implement both methods
class TV implements Screen {

	@Override
	public void LED() {

		System.out.println("TV has LED Screen");
	}

	@Override
	public void LCD() {

		System.out.println("TV has LCD Screen");

	}

}

/*
 * Test - Interface methods example
 */
public class Sample {

	public static void main(String[] args) {

		TV t = new TV();
		t.LED();
		t.LCD();
	}

}


Output:
TV has LED Screen
TV has LCD Screen

Exercise on Interface methods in Java

You can do the following exercise on interface method in java programming to polish your knowledge.

Exercise: Create a Shape interface having methods area () and perimeter (). Create 2 subclasses, Circle and Rectangle that implement the Shape interface. Create a class Sample with main method and demonstrate the area and perimeters of both the shape classes. You need to handle the values of length, breath, and radius in respective classes to calculate their area and perimeter.

View Solution

Related Posts