Java Interface
Data Abstraction in Java is also achieved by Java Interface. An Interface is a completely “abstract class” which is used to group related methods with empty bodies.
Example
//interface interface AnimalSound { public void animalSound(); public void sleep(); }
To access the interface methods, the interface must be “implemented” (like inherited) by another class using the implements keyword (instead of extends keyword).
Example
In the below example, we implemented the two interface methods animalSound() and sleep() in another classes Dog and Cow.
AnimalSound.java
//interface interface AnimalSound { public void animalSound(); public void sleep(); } class Dog implements AnimalSound{ public void animalSound(){ System.out.println("Dog makes bow bow sound"); } public void sleep(){ System.out.println("Zzzzz"); } } class Cow implements AnimalSound{ public void animalSound(){ System.out.println("Cow makes moo moo sound"); } public void sleep(){ System.out.println("Zzzzz"); } }
AnimalSoundClass.java
public class AnimalSoundClass { public static void main(String args[]){ AnimalSound myDog = new Dog(); AnimalSound myCow = new Cow(); myDog.animalSound(); myDog.sleep(); myCow.animalSound(); } }
Output
Dog makes bow bow sound Zzzzz Cow makes moo moo sound
Notes
Why Interface?
Multiple Interfaces
To implement multiple interfaces, we separate them with commas.
Example
We implement two interfaces in the MultipleInterface class:
FirstInterface.java
interface FirstInterface { public void firstMethod(); } interface SecondInterface { public void secondMethod(); } class MultipleInterfaces implements FirstInterface, SecondInterface { public void firstMethod() { System.out.println("First Method called"); } public void secondMethod() { System.out.println("Second Method called"); } }
MyMainJavaClass.java
public class MyMainJavaClass { public static void main(String args[]){ MultipleInterfaces myObj = new MultipleInterfaces(); myObj.firstMethod(); myObj.secondMethod(); } }
Output
First Method called Second Method called