Table of Contents
Interface in java programming language
An interface in Java similar a class but it is not a class. It is the blueprint of a class. An interface can contain any number of data-members and methods with an empty implementation.
A Java interface is just a collection of abstract methods interface instead of multiple inheritance.
All the methods of interface are abstract and should be overridden in subclass.
Why interfaces are needed in Java?
No multiple inheritance in Java – Cannot extend to more than one class at a time. Interfaces use Java instead of multiple inheritance because multiple inheritance is not supported in Java.
An interface can extend to another interface similar to the way that a class can extend to another class.
A class can implement more than one interface at a time.
The relationship between classes and interfaces
How to declare a interface
interface <interface_ame>{ //declare variables; //declare metods that abstract; }
public interface calc { //data member int age ; float salary; double total; boolean isEmpty //methods public void calculate (); public void total(float f1, float f2); }
Example programs
program 1
interface welcome // interface named welcome
{
void print();
}
class Class implements welcome{ //class named Class
public void print()
{
System.out.println(“welcome to java”);
}
public static void main (String args[]){ //main method in java
Class A=new Class();// object for class Class
A.print();
}
}
Program 2
interface office{
void display();
void print();
}
class staffs implements office
{
public void display()
{
System.out.println(“this is my display”);
}
public void print()
{
System.out.println(“this is my print”);
}
public static void main(String args[]){
staff obj=new staff();
obj.display();
obj.print();
}
}
Program 3
interface shape //interface
{
double pi=3.14;
void calculate(float f1, float f2);
}
class circle implements shape // class circle implement using interface
{
public void calculate(float x, float y)
{
System.out.println(“Area of circle:”+(pi*x*y));
}
}
class regrangle implements shape // class regtangle implement using interface
{
public void calculate(float x, float y)
{
System.out.println(“Area of regtangle:”+(x*y));
}
}
class multipleinherit
{
public static void main(String args[])
{
shape s1; // create reference for interface
circle c1=new circle(); //create object for circle class
regrangle r1=new regrangle(); //create object for regtangle class
s1=c1; //assign object c1 to interface
s1.calculate(10,6); //called method with argument
s1=r1;
s1.calculate(15,6); //called method with argument
}
}