Object Oriented Programming: Unit II: Inheritance, Packages and Interfaces

Implementing Interface

with Example Java Programs

It is necessary to create a class for every interface.The class must be defined in the following form while using the interface

Implementing Interface

• It is necessary to create a class for every interface.

• The class must be defined in the following form while using the interface

class Class_name extends superclass_name

implements interface_name1,interface_name2,...

{

//body of class

}

• Let us learn how to use interface for a class baland you dont

Step 1: Write following code and save it as my_interface.java

public interface my_interface

{

void my_method(int val);

}

Do not compile this program. Simply save it.

Step 2: Write following code in another file and save it using InterfaceDemo.java

Java Program[Interface Demo.java]

class A implements my_interface

{

public void my_method(int i)

{

System.out.println("\n The value in the class A: "+i);

}

public void another_method() //Defining another method not declared in interface

{

System.out.println("\nThis is another method in class A");

}

}

class Interface Demo

{

public static void main(String args[])

{

my_interface obj=new A();

//or A obj=new A() is also allowed

A obj1=new A();

obj.my_method(100);

obj1.another_method();

}

}

Step 3: Compile the program created in step 2 and get the following output

F:\test>javac InterfaceDemo.java

F:\test>java InterfaceDemo

The value in the class A: 100

This is another method in class A

Program Explanation:

In above program, the interface my_interface declares only one method i.e. my_method. This method can be defined by class A. There is another method which is defined in class A and that is another_method. Note that this method is not declared in the interface my_interface. That means, a class can define any additional method which is not declared in the interface.

Various ways of interface implementation

• The design various ways by which the interface can be implemented by the class is represented by following Fig. 2.17.1.

• The variables can be assigned with some values within the interface. They are implicitly final and static. Even if you do not specify the variables as final and static they are assumed to be final and static.

• Interface variables are static because Java interfaces cannot be instantiated. Hence the value of the variable must be assigned in a static context in which no instance exists. The final modifier indicates that the value assigned to the interface variable is a true constant that cannot be re-assigned by program code.

Review Question

1.What is an interface? Write a Java program to illustrate the use of interface. Give self explanatory comments in your program. AU: Dec.-14, Marks 8

Object Oriented Programming: Unit II: Inheritance, Packages and Interfaces : Tag: : with Example Java Programs - Implementing Interface