Tutoriallearn.com
Easy Learning
Search Tutoriallearn.com :
Interface is a collection of function declarations (abstract functions). The function declaration has name of the function and type of arguments that will be passed to the function.
Interface is related to a particular task. For example, developer may create an interface for printing the document (say Print). Then 'Print' interface consists of a set
of function declarations that are able to print document.
To create an interface, following two steps are required:
Step 1: Define an interface with declaration of the functions (abstract class)
Step 2: Implement an interface in the class
Following is explanation of each step with example:
Step 1: Define an interface with declaration of the function
To define a function, use the keyword 'interface', for example:
interface Print {
void PrintData(int PrintMode);
}
In this example, interface name is 'Print'. It consists of a function named 'PrintData' and one argument named 'PrintMode' of type 'int'.
class Computer implements Print {
public void PrintData (int a) {
System.out.println ("Printer with mode" + a);
}
}
In this example, a class named 'Computer' is defined which implements the interface 'Print'.
interface Disp{
void DispData();
}
interface Print {
void PrintData(int PrintMode);
}
class Computer implements Print, Disp {
public void PrintData (int a) {
System.out.println ("Printer with mode" + a);
}
public void DispData () {
System.out.println ("Hello! Learner");
}
public static void main(String args[])
{
Computer c1 = new Computer();
c1.PrintData(12);
c1.DispData();
}
}
In this program, two interfaces Disp and Print are defined.
Class Computer implements both interfaces. It provides
function body of both functions declared in interfaces.
An interface may have body of a function. But it should be declared as default.
interface Disp {
default void DispData()
{
System.out.println("Function body within interface"); // Defining body of function in interface
}
}
interface Print {
void PrintData(int PrintMode);
}
class Computer implements Print, Disp {
public void PrintData (int a) {
System.out.println ("Printer with mode" + a);
}
public static void main(String args[])
{
Computer c1 = new Computer();
c1.PrintData(12);
c1.DispData(); //DispData function body is defined in interface
}
}
Interface Disp consists of one function named DispData () with its body .