[go: up one dir, main page]

0% found this document useful (0 votes)
62 views35 pages

Interfaces

Download as docx, pdf, or txt
Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1/ 35

Interfaces:

 An interface in Java is a blueprint of a class.


 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 inheritance in Java.
 Java Interface also represents the IS-A relationship.
 It cannot be instantiated just like the abstract class.
 Since Java 8, we can have default and static methods in an interface and
Since Java 9, we can have private methods in an interface.

Note: - It has static constants and abstract methods.

Def1: Any service requirement specification (srs) is called an interface.

Example1: Sun people responsible to define JDBC API and database vendor will
provide implementation for that.

Diagram:
Example2: Sun people define Servlet API to develop web applications web server
vendor is responsible to provide implementation.

Diagram:

Def2: From the client point of view an interface define the set of services what is
expecting. From the service provider point of view an interface defines the set of
services what is offering. Hence an interface is considered as a contract between
client and service provider.

Example: ATM GUI screen describes the set of services what bank people
offering, at the same time the same GUI screen the set of services what customer is
expecting hence this GUI screen acts as a contract between bank and customer.

Def3: Inside interface every method is always abstract whether we are declaring or
not hence interface is considered as 100% pure abstract class.

Summery def: Any service requirement specification (SRS) or any contract


between client and service provider or 100% pure abstract classes is considered as
an interface.
Why do we use interface?

 It is used to achieve total abstraction.


 Since java does not support multiple inheritance in case of class, but by
using interface it can achieve multiple inheritance.
 It is also used to achieve loose coupling.

How to declare an interface?

An interface is declared by using the interface keyword. It provides total


abstraction; means all the methods in an interface are declared with the empty
body, and all the fields are public, static and final by default. A class that
implements an interface must implement all the methods declared in the interface.

Syntax:

interface <interface_name>

// declare constant fields

// declare methods that abstract

// by default.

public interface Printable

public abstract void wish();//in interface every method is public & abstract

void msg();//public abstract


}

abstract class Greet implements Printable

public void wish()

System.out.println("Hello World! Good morning");

public class Wish extends Greet

public void msg()

System.out.println("Hello World! have a nice day");

public static void main(String[] args)

Wish w=new Wish();

w.wish();

w.msg();
}

Internal addition by the compiler

Note:-The Java compiler adds public and abstract keywords before the interface
method. Moreover, it adds public, static and final keywords before data members.

In other words, Interface fields are public, static and final by default, and the
methods are public and abstract.

Ex:-

interface Printable {

void wish();

class Greet implements printable{

public void wish(){

System.out.println("Hello");

public static void main(String args[]){

Greet obj = new Greet ();


obj.wish();

Output:

Hello

Java Interface Example: Bank

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();

System.out.println("ROI: "+b.rateOfInterest());

}}

Output:

ROI: 9.15

Java Interface Example: Drawable

File: TestInterface1.java

//Interface declaration: by first user

interface Drawable{

void draw();

//Implementation: by second user

class Rectangle implements Drawable{

public void draw(){

System.out.println("drawing rectangle");

}
class Circle implements Drawable{

public void draw(){

System.out.println("drawing circle");

//Using interface: by third user

class TestInterface1{

public static void main(String args[]){

Drawable d=new Circle();//In real scenario, object is provided by method e.g.


getDrawable()

d.draw();

}}

Declaration and implementation of an interface:

Note1:

Whenever we are implementing an interface compulsory for every method of that


interface we should provide implementation otherwise we have to declare class as
abstract in that case child class is responsible to provide implementation for
remaining methods.

Note2:

Whenever we are implementing an interface method compulsory it should be


declared as public otherwise we will get compile time error.
Example:

interface Interf{

void m1();

void m2();

class SubServiceProvider extends ServiceProvider{

Output:

Compile time error.

D:\Java>javac SubServiceProvider.java

SubServiceProvider.java:1:

SubServiceProvider is not abstract and does not override

abstract method methodTwo() in Interf

class SubServiceProvider extends ServiceProvider

The relationship between classes and interfaces


A class extends another class, an interface extends another interface, but a class
implements an interface. but one interface cannot implements another interface

Extends vs implements:

A class can extends only one class at a time.

Example:

class One{

public void m1(){

class Two extends One{

A class can implements any no. Of interfaces at a time.

Example:
interface One{

public void m1();

interface Two{

public void m2();

class Three implements One,Two{

public void m1(){

public void m2(){

A class can extend a class and can implement any no. Of interfaces
simultaneously.

interface One{

void m1();

class Two{

public void m2(){

}
}

class Three extends Two implements One{

public void m1(){

An interface can extend any no. Of interfaces at a time.

Example:

interface One{

void m1();

interface Two{

void m2();

interface Three extends One,Two

Interface methods:
Every method present inside interface is always public and abstract whether we are
declaring or not. Hence inside interface the following method declarations are
equal.

 void m1();
 public void m1();
 abstract void m1();
 public abstract void m1();

public: To make this method available for every implementation class.

abstract: Implementation class is responsible to provide implementation .

As every interface method is always public and abstract we can't use the following
modifiers for interface methods.

Private, protected, final, static, synchronized, native, strictfp.

Interface variables:

 An interface can contain variables


 The main purpose of interface variables is to define requirement level
constants.
 Every interface variable is always public static and final whether we are
declaring or not.

Example:

interface interf{

int x=10;
}

public: To make it available for every implementation class.

static: Without existing object also we have to access this variable.

final: Implementation class can access this value but cannot modify.

Hence inside interface the following declarations are equal.


int x=10;
public int x=10;
static int x=10;
final int x=10;
public static int x=10;
public final int x=10;
static final int x=10;
public static final int x=10;

As every interface variable by default public static final we can't declare with the
following modifiers.
 Private
 Protected
 Transient
 Volatile

For the interface variables compulsory we should perform initialization at the time
of declaration only otherwise we will get compile time error.

Example:
interface Interf{

int x;

Output:

Compile time error.

D:\Java>javac Interf.java

Interf.java:3: = expected int x;

Which of the following declarations are valid inside interface?

1. int x;

2. private int x=10;

3. public volatile int x=10;

4. public transient int x=10;

5. public static final int x=10;

Ans: 5

Interface variables can be access from implementation class but cannot be


modified.

Example:

interface Interf{

int x=10;

}
Example 2:

class Test implements Interf{

public static void main(String args[]){

int x=20;

//here we declaring the variable x.

System.out.println(x);

Output:

D:\Java>javac Test.java

D:\Java>java Test
20

Multiple inheritance in Java by interface:

If a class implements multiple interfaces, or an interface extends multiple


interfaces, it is known as multiple inheritance.

interface Printable{

void print();

interface Showable{

void show();

class A7 implements Printable,Showable{

public void print(){

System.out.println("Hello");

}
public void show(){

System.out.println("Welcome");

public static void main(String args[]){

A7 obj = new A7();

obj.print();

obj.show();

Output:Hello

Welcome

Q) Multiple inheritance is not supported through class in java, but it is


possible by an interface, why?

As we have explained in the inheritance chapter, multiple inheritance is not


supported in the case of class because of ambiguity. However, it is supported in
case of an interface because there is no ambiguity. It is because its implementation
is provided by the implementation class.

interface Printable{

void print();
}

interface Showable{

void print();

class TestInterface implements Printable, Showable{

public void print(){

System.out.println("Hello");

public static void main(String args[]){

TestInterface obj = new TestInterface();

obj.print();

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 an interface, but one interface extends another interface.

interface Printable{

void print();

interface Showable extends Printable{

void show();

class TestInterface implements Showable{

public void print(){

System.out.println("Hello");

public void show(){

System.out.println("Welcome");

public static void main(String args[]){

TestInterface obj = new TestInterface();

obj.print();

obj.show();
}

Output:

Hello

Welcome

Interface naming conflicts:

Method naming conflicts:

Case 1:

If two interfaces contain a method with same signature and same return type in the
implementation class only one method implementation is enough.

Example 1:

interface Left{

public void m1();

Example 2:

interface Right{

public void m1();

Example 3:

class Test implements Left,Right{


public void m1(){

}}

Output:

D:\Java>javac Left.java

D:\Java>javac Right.java

D:\Java>javac Test.java

Case 2:

If two interfaces contain a method with same name but different arguments in the
implementation class we have to provide implementation for both methods and
these methods acts as a overloaded methods.

Example 1:

interface Left{

public void m1();

Example 2:

interface Right{

public void m1(int i);

}
Example 3:

class Test implements Left,Right{

public void m1(){

public void m1(int i)

}}

Output:

D:\Java>javac Left.java

D:\Java>javac Right.java

D:\Java>javac Test.java

Case 3:

If two interfaces contain a method with same signature but different return types
then it is not possible to implement both interfaces simultaneously.

Example 1:

interface Left{

public void m1();

}
Example 2:

interface Right{

public int m1(int i);

We can't write any java class that implements both interfaces simultaneously.

Is a java class can implement any no. Of interfaces simultaneously?

Yes, except if two interfaces contains a method with same signature but different
return types.

Variable naming conflicts:

Two interfaces can contain a variable with the same name and there may be a
chance variable naming conflicts but we can resolve variable naming conflicts by
using interface names.

Example 1:

interface Left{

int x=888;

Example 2:

interface Right{

int x=999;

}
Example 3:

class Test implements Left,Right{

public static void main(String args[]){

//System.out.println(x);

System.out.println(Left.x);

System.out.println(Right.x);

Output:

D:\Java>javac Left.java

D:\Java>javac Right.java

D:\Java>javac Test.java

D:\Java>java Test

888

999

Marker interface / Tagged interface:

If an interface doesn't contain any methods and by implementing that interface if


our objects will get some ability such type of interfaces are called Marker interface
(or) Tag interface (or) Ability interface.

/How Serializable interface is written?

public interface Serializable{


}

Example:

Serializable

Cloneable

RandomAccess ///These are marked for some ability

SingleThreadModel

Example 1:

By implementing Serilaizable interface we can send that object across the network
and we can save state of an object into a file.

Example 2:

By implementing SingleThreadModel interface Servlet can process only one client


request at a time so that we can get "Thread Safety".

Example 3:

By implementing Cloneable interface our object is in a position to provide exactly


duplicate cloned object.

Without having any methods in marker interface how objects will get ability?

Internally JVM is responsible to provide required ability.

Why JVM is providing the required ability in marker interfaces?

To reduce complexity of the programming.

Is it possible to create our own marker interface?

Yes, but customization of JVM must be required.


Ex : Sleepable , Jumpable ,

What is the difference between interface, abstract class and concrete class?

When we should go for interface, abstract class and concrete class?

 If we don't know anything about implementation just we have requirement


specification then we should go for interface.
 If we are talking about implementation but not completely (partial
implementation) then we should go for abstract class.
 If we are talking about implementation completely and ready to provide
service then we should go for concrete class.

What is the Difference between interface and abstract class?


Abstract class Interface
1) Abstract class can have abstract and Interface can have only abstract methods.
non-abstract methods. Since Java 8, it can have default and static
methods also.

2) Abstract class doesn't support Interface supports multiple inheritance.


multiple inheritance.

3) Abstract class can have final, non- Interface has only static and final
final, static and non-static variables. variables.

4) Abstract class can provide the Interface can't provide the implementation


implementation of interface. of abstract class.

5) The abstract keyword is used to The interface keyword is used to declare


declare abstract class. interface.

6) An abstract class can extend another An interface can extend another Java


Java class and implement multiple Java interface only.
interfaces.

7) An abstract class can be extended An interface can be implemented using


using keyword "extends". keyword "implements".

8) A Java abstract class can have class Members of a Java interface are public by


members like private, protected, etc. default.

9)Example: Example:
public abstract class Shape{ public interface Drawable{
public abstract void draw(); void draw();
} }
Example of abstract class and interface in Java

//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(){System.out.println("I am C");}

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


rest of the methods

class M extends B{

public void a(){System.out.println("I am a");}

public void b(){System.out.println("I am b");}


public void d(){System.out.println("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

We can't create object for abstract class but abstract class can contain
constructor what is the need?
Abstract class constructor will be executed whenever we are creating child class
object to perform initialization of child object.

Every method present inside interface is abstract but in abstract class also we
can take only abstract methods then what is the need of interface concept ?

We can replace interface concept with abstract class. But it is not a good
programming practice. We are misusing the roll of abstract class. It may create
performance problems also.

(this is just like recruiting IAS officer for sweeping purpose)

Why abstract class can contain constructor whereas interface doesn't contain
constructor?

The main purpose of constructor is to perform initialization of an object i.e.,


provide values for the instance variables, Inside interface every variable is always
static and there is no chance of existing instance variables. Hence constructor is not
required for interface.

But abstract class can contains instance variable which are required for the child
object to perform initialization for those instance variables constructor is required
in the case of abstract class.

The Purpose of Constructor is

To Initialize an Object but Not to Create an Object.

Whenever we are creating an Object after Object Creation automatically

Constructor will be executed to initialize that Object.

Object Creation by New Operator and then Initialization by Constructor.


 Whenever we are creating Child Class Object automatically Parent
Constructor will be executed but Parent Object won’t be created.
 The Purpose of Parent Constructor Execution is to Initialize Child Object
Only. Of Course for the Instance Variables which are inheriting from parent
Class.

Any Way we can’t Create Object for Abstract Class and Interface. But
Abstract Class can contain Constructor but Interface doesn’t why?
 The Main Purpose of Constructor is to Perform Initialization of an Object
i.e. to
 Provide Values for Instance Variables.
 Abstract Class can contain Instance Variables which are required for Child
Class
 Object to Perform Initialization of these Instance Variables Constructor is
required Inside Abstract Class.
 But Every Variable Present inside Interface is Always public, static and final
whether we are declaring OR Not and Every Interface Variable we should
Perform
 Initialization at the Time of Declaration and Hence inside Interface there is
No Chance of existing Instance Variable.
 Due to this Initialization of Instance Variables Concept Not Applicable for
Interfaces.
 Hence Constructor Concept Not required for Interface.

You might also like