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 inheritance in Java.
In other words, you can say that interfaces can have abstract methods and variables. It cannot have a method body.
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.
Since Java 9, we can have private methods in an 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 inheritance.
- It can be used to achieve loose coupling.
Example
Speakable.java
public interface Speakable{
public String speak();
}
Animal.java
public class Animal{
protected String kind;
public Animal(){};
public String toString(){
return "I am a" + kind + "and I go" + ((Speakable)this).speak();
}
}
Cat.java
public class Cat extends Animal implements Speakable{
public Cat(){
kind = "cat";}
public String speak(){
return "meow";}
}
Cow.java
public class Cow extends Animal implements Speakable{
public Cow(){
kind = "cow";}
public String speak(){
return "moo";}
}
TestAnimal.java
public class AnimalInterfaceTest{
public static void main(String[] args) {
Animal neko = new Cat();
Animal ushi = new Cow();
if (neko instanceof Cat){
System.out.println( neko.toString());}
else{
System.out.println("error!");
}
if (ushi instanceof Cow){
System.out.println( ushi.toString());}
else{
System.out.println("error!");
}
}
}
0 Comments