Skip to main content

Practical-27

Write a java program which implements Interface.

Introduction

Java implements multiple Interfaces using inheritance to re-use code of several classes. An interface is a contract between the class and the outside world and Java requires that the class obeys the contract. Implementing an interface means that your class agrees to carry out a certain contract specified by the interface. In other words, it requires that your class must fulfill the promises or contracts made by the interface.

Code

public interface InterfaceExample {
void print();
int add(int x, int y);
}
public class Demo implements InterfaceExample {
public void print() {
System.out.println("print method implementation");
}
public int add(int x, int y) {
return x+y;
}
}
public class Main {
public static void main(String[] args) {
Demo d = new Demo();
d.print();
int result = d.add(5, 7);
System.out.println("Result = "+result);
}
}

Output

print method implementation
Result = 12

Explanation

The code implements the InterfaceExample interface by implementing its two methods. It then creates object of Demo class and calls the two methods associated with it.