Java interface is an abstract
class which provides data abstraction. Abstraction is a way to provide users with only relevant and essential information and hide the rest.
Java interface is an abstract class which is used to group related methods, classes or data with empty bodies.
An interface cannot be instantiated ie., you cannot create an object of an interface. However, classes may have an object.
An interface is implemented without any constructors.
Each field in an interface must be declared final and static.
An interface is implemented by another class. It is never extended by a class.
An interface, however, may extend multiple interfaces.
This example shows how an interface is implemented by a class. (Pig implements Animal)
// Interfaceinterface Animal {public void animalSound(); // interface method (does not have a body)public void sleep(); // interface method (does not have a body)}// Pig "implements" the Animal interfaceclass Pig implements Animal {public void animalSound() {// The body of animalSound() is provided hereSystem.out.println("The pig is calling you: WEE WEEE WEEEEE");}public void sleep() {// The body of sleep() is provided hereSystem.out.println("Sleep Sound: ZzzzzzzZZzzzzZZzzz");}}class main {public static void main(String[] args) {Pig p = new Pig(); // Create a Pig objectp.animalSound();p.sleep();}}
This example runs for multiple interfaces problem. There are two interfaces which are implemented by a single class.
interface InterfaceOne {public void Method(); // interface method}interface InterfaceTwo {public void Method2(); // interface method}// Demo "implements" InterfaceOne and InterfaceTwoclass Demo implements InterfaceOne, InterfaceTwo {public void Method() {System.out.println("Text One");}public void Method2() {System.out.println("Text two");}}class main {public static void main(String[] args) {Demo Obj = new Demo();Obj.Method();Obj.Method2();}}
Free Resources