Monday, 28 November 2016

Program to create a interface 'printable' and implement it in 'InterfaceDemo' class

Interface looks like class but it is not a class. An interface can have methods and variables just like the class but the methods declared in interface are by default abstract (only method signature, no body). Also, the variables declared in an interface are public, static & final by default. The interface in java is a mechanism to achieve fully abstraction.

The class that implements interface must implement all the methods of that interface. Also, java programming language does not support multiple inheritance, using interfaces we can achieve this as a class can implement more than one interfaces. It cannot be instantiated just like abstract class. To achieve multiple inheritance in Java you have to use interface. The syntax for declaring interface is given below:
interface <interface-name> {
    // variable declarations
 // Method declarations (no implementation)
}

The implements keyword is used to for implementing interface and extends keyword is used to extend the class. The syntax for extending class and implementing interface is:
class <subclass-name> extends <superclass-name> implements <interface-name> {

 // Body of subclass
}

In this program, we have created an interface printable which has one method print( ) without implementation (body). Then we declare the class InterfaceDemo which implements printable interface and override (implement) the print( ) method in it. You must override all the methods which a interface contains. In main( ) method we have created an object of InterfaceDemo class and call the print( ) method.


PROGRAM
interface printable {
 
 void print();
}

public class InterfaceDemo implements printable {

 @Override
 public void print() {
  
  System.out.println("Hello");
 }
 
 public static void main(String[] args) {
  
  InterfaceDemo i = new InterfaceDemo();
  i.print();
 }
}
OUTPUT
C:\>javac InterfaceDemo.java
C:\>java InterfaceDemo
Hello

No comments:

Post a Comment