interface

To achieve abstraction we have two way

  1. Abstract class
  2. Interface

We learn about the abstract class in the previous article

In this, we will learn about the interface

What is the interface:

The interface is  java keyword which is used to make interface class

The interface is the blueprint of the class which tells the class what to do.

By interface, we can achieve 100% abstraction

Uses of Interface:

  • To achive 100% abstraction
  • To achive multipe inheritance
  • To achive low coupling

Syntex of interface:

interface Interfacename {
    //methods
    //field
}

There is some rule of abstraction

  • In the interface, we can only declare abstract methods with public access specifier only
  • We can’t create the object of the interface
  • We can’t  create a body of methods in the interface
  • to inherit interface we use implement keyword
  • if you use Java 8th version  you  can create default methods in interface with the body
  • if you use Java 8th version  you  can create public static methods in interface with the body
  • if you use Java 9th version  you  can create private methods in the interface

See an example of the interface

interface Dog{  
 
 void run(); 

}  
public class Puppy implements Dog{  
    
public void run()
{
    System.out.println("puppy running");
    
}  
  
public static void main(String args[]){
    
Puppy obj = new Puppy();  
obj.run();  
 }  
}

Multiple inheritance example

interface Printable{  
void print();  
}  
interface Showable{  
void show();  
}  
 public 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();  
 }  
}


SHARE THIS PAGE





Important Link