Interfaces are syntactically similar to classes, but their methods are declared without any body. i.e. Using interface we can fully abstract (i.e. hide) a class interface from its implementation. Interfaces are created using the keyword interface as shown in the below example -
Defining an Interface Example:
void add(int param, int param); //Methods in interface wont have any body
Methods in Interface wont have any body. Classes in Java can implement the interface as shown below. When a Class implements an interface, the unimplemented methods of Interface must be implemented by the Class as shown below -
Class Implementing an Interface Example:
class ClassOne implements Sample
public void add(int a, int b)
System.out.println("The sum of a and b is "+ (a+b));
Hence, when any Class implements any interface, all the unimplemented methods of Implemented interface must be implemented by the Class.
Lets implement this on Eclipse IDE (i.e A class implementing an interface)
1. Create a Java Project 'Project B2' as shown below:
5. Add a method to the interface as shown below and save:
9. Observe that the output is displayed in the console as shown below:
Click here to download the project containing the 'Sample' interface, 'ClassOne' and 'InterfaceDemo' class files used in this post (You can download this project and import into Eclipse IDE on your machine)
What happens when a class implements an interface but implements one out of two methods of an interface. Error "This class must implement this method 'method name' " should be displayed if all the methods of an interface are not implemented by a class.
Lets implement this on Eclipse IDE:
1. In the above project 'Project B2', add one more method template to the 'Sample' interface as shown below and save:
3. Now lets implement the sub( ) method of 'Sample' interface in 'ClassOne' class and find out whether the displayed error gets resolved or not as shown below:
Please comment below to feedback or ask questions.
'Class implementing multiple Interfaces' will be explained in the next post.