0% found this document useful (0 votes)
4 views9 pages

Interface in Java

An interface in Java is a blueprint that defines abstract methods and static constants, used to achieve abstraction and multiple inheritance. Interfaces cannot be instantiated and must be implemented by classes that provide method bodies. Since Java 8, interfaces can include default and static methods, and they can also contain nested interfaces and classes.

Uploaded by

indranilrocstar
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views9 pages

Interface in Java

An interface in Java is a blueprint that defines abstract methods and static constants, used to achieve abstraction and multiple inheritance. Interfaces cannot be instantiated and must be implemented by classes that provide method bodies. Since Java 8, interfaces can include default and static methods, and they can also contain nested interfaces and classes.

Uploaded by

indranilrocstar
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Interface in Java

An interface in java is a blueprint of a class. It has static constants and abstract methods. The interface in
java is a mechanism to achieve abstraction. There can be only abstract methods in the java interface not
method body. It is used to achieve abstraction and multiple inheritances in Java.

In other words, you can say that interfaces can have methods and variables but the methods declared in
interface contain only method signature, not body. Java Interface also represents IS-A relationship.
It cannot be instantiated just like abstract class.

Why use Java interface?


There are mainly three reasons to use interface. They are given below.
• It is used to achieve abstraction.
• By interface, we can support the functionality of multiple inheritances.
• It can be used to achieve loose coupling.

How to declare interface?


Interface is declared by using interface keyword. It provides total abstraction; means all the methods in
interface are declared with empty body and are public and all fields are public, static and final by default. A
class that implement interface must implement all the methods declared in the interface.
Syntax:
interface <interface_name>{
// declare constant fields
// declare methods that abstract by default.
}

Java 8 Interface Improvement


Since Java 8, interface can have default and static methods which are discussed later.

Internal addition by compiler


The java compiler adds public and abstract keywords before the interface method. More, it adds
public, static and final keywords before data members.
In other words, Interface fields are public, static and final by default, and methods are public and abstract.
Understanding relationship between classes and interfaces
As shown in the figure given below, a class extends another class, an interface extends another interface but
a class implements an interface.

Java Interface Example


import [Link].*;
interface Figure {
double getArea(double x, double y );
}

class Rectangle implements Figure {

public double getArea(double d1, double d2) {

return (d1*d2);
}
}

class Triangle implements Figure {

public double getArea(double d1, double d2) {


return(0.5*d1*d2);
}
}

class InterfaceRTPDemo1 {
public static void main(String args[]) {
Scanner sc = new Scanner([Link]);
[Link]("Enter length & breadth of a Rectangle:");
double l = [Link]();
double b = [Link]();
Figure ref;
ref = new Rectangle();
[Link]([Link](l, b));
[Link]("Enter base & height of a Triangle:");
l = [Link]();
b = [Link]();
ref = new Triangle();;
[Link]([Link](l,b));
}
}

Java Interface Example


In this example, Printable interface has only one method, its implementation is provided in the A class.
interface printable{
void print();
}
class A6 implements printable{
public void print(){
[Link]("Hello");
}
public static void main(String args[]){
A6 obj = new A6();
[Link]();
}
}
Output:
Hello

Java Interface Example: Drawable


In this example, Drawable interface has only one method. Its implementation is provided by Rectangle and
Circle classes. In real scenario, interface is defined by someone but implementation is provided by different
implementation providers. And, it is used by someone else. The implementation part is hidden by the user
which uses the interface.

File: [Link]
//Interface declaration: by first user
interface Drawable{
void draw();
}
//Implementation: by second user
class Rectangle implements Drawable{
public void draw(){[Link]("drawing rectangle");}
}
class Circle implements Drawable{
public void draw(){[Link]("drawing circle");}
}
//Using interface: by third user
class TestInterface1{
public static void main(String args[]){
Drawable d=new Circle();
//object is provided by method e.g. getDrawable()
[Link]();
}
}
Output:
drawing circle

Java Interface Example: Bank


Let's see another example of java interface which provides the implementation of Bank interface.
File: [Link]
interface Bank{
float rateOfInterest();
}
class SBI implements Bank{
public float rateOfInterest(){return 9.15f;}
}
class PNB implements Bank{
public float rateOfInterest(){return 9.7f;}
}
class TestInterface2{
public static void main(String[] args){
Bank b=new SBI();
[Link]("ROI: "+[Link]());
}
}
Output:
ROI: 9.15

Multiple inheritance in Java by interface


If a class implements multiple interfaces, or an interface extends multiple interfaces i.e. known as multiple
inheritance.
interface Printable{
void print();
}
interface Showable{
void show();
}
class A7 implements Printable,Showable{
public void print(){[Link]("Hello");}
public void show(){[Link]("Welcome");}

public static void main(String args[]){


A7 obj = new A7();
[Link]();
[Link]();
}
}
Output: Hello
Welcome

Q) Multiple inheritance is not supported through class in java but it is possible by interface,
why?
As we have explained in the inheritance chapter, multiple inheritance is not supported in case of class
because of ambiguity. But it is supported in case of interface because there is no ambiguity as
implementation is provided by the implementation class. For example:
interface Printable{
void print();
}
interface Showable{
void print();
}
class TestInterface3 implements Printable, Showable{
public void print(){[Link]("Hello");}
public static void main(String args[]){
TestInterface3 obj = new TestInterface3();
[Link]();
}
}
Output:
Hello
As you can see in the above example, Printable and Showable interface have same methods but its
implementation is provided by class TestTnterface1, so there is no ambiguity.

Interface inheritance
A class implements interface but one interface extends another interface.
interface Printable{
void print();
}

interface Showable extends Printable{


void show();
}
class TestInterface4 implements Showable{
public void print(){[Link]("Hello");}
public void show(){[Link]("Welcome");}
public static void main(String args[]){
TestInterface4 obj = new TestInterface4();
[Link]();
[Link]();
}
}
Output:
Hello
Welcome
Java 8 Default Method in Interface
Since Java 8, we can have method body in interface. But we need to make it default method. Let's see an
example:
File: [Link]
interface Drawable{
void draw();
default void msg(){[Link]("default method");}
}
class Rectangle implements Drawable{
public void draw(){[Link]("drawing rectangle");}
}
class TestInterfaceDefault{
public static void main(String args[]){
Drawable d=new Rectangle();
[Link]();
[Link]();
}
}
Output:
drawing rectangle
default method

Java 8 Static Method in Interface


Since Java 8, we can have static method in interface. Let's see an example:
File: [Link]
interface Drawable{
void draw();
static int cube(int x){return x*x*x;}
}
class Rectangle implements Drawable{
public void draw(){[Link]("drawing rectangle");}
}
class TestInterfaceStatic{
public static void main(String args[]){
Drawable d=new Rectangle();
[Link]();
[Link]([Link](3));
}
}
Output:
drawing rectangle
27

Q) What is marker or tagged interface?


An interface which has no member is known as marker or tagged interface. For example: Serializable,
Cloneable, Remote etc. They are used to provide some essential information to the JVM so that JVM may
perform some useful operation.
//How Serializable interface is written?
public interface Serializable{
}

Nested Interface in Java


Note: An interface can have another interface i.e. known as nested interface. For example:
interface printable{
void print();
interface MessagePrintable{
void msg();
}
}

Java Nested Interface


An interface i.e. declared within another interface or class is known as nested interface. The nested
interfaces are used to group related interfaces so that they can be easy to maintain. The nested interface must
be referred by the outer interface or class. It can't be accessed directly.

Points to remember for nested interfaces


There are given some points that should be remembered by the java programmer.
• Nested interface must be public if it is declared inside the interface but it can have any access
modifier if declared within the class.
• Nested interfaces are declared static implicitly.

Syntax of nested interface which is declared within the interface


interface interface_name{
...
interface nested_interface_name{
...
}
}

Syntax of nested interface which is declared within the class


class class_name{
...
interface nested_interface_name{
...
}
}

Example of nested interface which is declared within the interface


In this example, we are going to learn how to declare the nested interface and how we can access it.
interface Showable{
void show();
interface Message{
void msg();
}
}
class TestNestedInterface1 implements [Link]{
public void msg(){[Link]("Hello nested interface");}

public static void main(String args[]){


[Link] message=new TestNestedInterface1();
//upcasting here
[Link]();
}
}
Output: hello nested interface
As you can see in the above example, we are accessing the Message interface by its outer interface
Showable because it cannot be accessed directly. It is just like almirah inside the room, we cannot access the
almirah directly because we must enter the room first. In collection framework, sun microsystem has
provided a nested interface Entry. Entry is the sub interface of Map i.e. accessed by [Link].

Internal code generated by the java compiler for nested interface Message
The java compiler internally creates public and static interface as displayed below:.
public static interface Showable$Message
{
public abstract void msg();
}

Example of nested interface which is declared within the class


Let's see how can we define an interface inside the class and how can we access it.
class A{
interface Message{
void msg();
}
}

class TestNestedInterface2 implements [Link]{


public void msg(){[Link]("Hello nested interface");}
public static void main(String args[]){
[Link] message=new TestNestedInterface2();//upcasting here
[Link]();
}
}
Output: hello nested interface

Can we define a class inside the interface?


Yes, If we define a class inside the interface, java compiler creates a static nested class. Let's see how can we
define a class within the interface:
interface M{
class A{}
}
Example:
interface Library {
void issueBook(Book b);
void retrieveBook(Book b);
public class Book {
int bookId;
String bookName;
int issueDate;
int returnDate;
}
}
public class Sample implements Library {
public void issueBook(Book b) {
[Link]("Book Issued");
}
public void retrieveBook(Book b) {
[Link]("Book Retrieved");
}
public static void main(String args[]) {
Sample obj = new Sample();
[Link](new [Link]());
[Link](new [Link]());
}
}

Difference between abstract class and interface


Abstract class and interface both are used to achieve abstraction where we can declare the abstract methods.
Abstract class and interface both can't be instantiated.
But there are many differences between abstract class and interface that are given below.
Abstract class Interface
1) Abstract class can have abstract and non- Interface can have only abstract methods. Since Java
abstract methods. 8, it can have default and static methods also.
2) Abstract class doesn't support multiple Interface supports multiple inheritance.
inheritance.
3) Abstract class can have final, non-final, Interface has only static and final variables.
static and non-static variables.
4) Abstract class can provide the Interface can't provide the implementation of
implementation of interface. abstract class.
5) The abstract keyword is used to declare The interface keyword is used to declare interface.
abstract class.
6) An abstract classcan extend another Java An interface can extend another Java interface only.
class and implement multiple Java interfaces.
7) An abstract classcan be extended using An interface classcan be implemented using
keyword ?extends?. keyword ?implements?.
8) A Javaabstract classcan have class members Members of a Java interface are public by default.
like private, protected, etc.
9)Example: Example:
public abstract class Shape{ public interface Drawable{
public abstract void draw(); void draw();
} }
Simply, abstract class achieves partial abstraction (0 to 100%) whereas interface achieves fully abstraction
(100%).
Example of abstract class and interface in Java
Let's see a simple example where we are using interface and abstract class both.
//Creating interface that has 4 methods
interface A{
void a();//bydefault, public and abstract
void b();
void c();
void d();
}

//Creating abstract class that provides the implementation of one method


of A interface
abstract class B implements A{
public void c(){[Link]("I am C");}
}

//Creating subclass of abstract class, now we need to provide the implem


entation of rest of the methods
class M extends B{
public void a(){[Link]("I am a");}
public void b(){[Link]("I am b");}
public void d(){[Link]("I am d");}
}

//Creating a test class that calls the methods of A interface


class Test5{
public static void main(String args[]){
A a=new M();
a.a();
a.b();
a.c();
a.d();
}
}
Output:
I am a
I am b
I am c
I am d

You might also like