What is interface in Java


Interface looks like a class but it is not a class. An interface can have methods and variables just like the class but the methods declared in interface are by default abstract (only method signatures, no body, see: Java abstract method). As mentioned above they are used for full abstraction. Since methods in interfaces do not have body, they have to be implemented by the class before you can access them.

The class that implements interface must implement all the methods of that interface. Also, java programming language does not allow you to extend more than one class, however you can implement more than one interface in your class.

Source Code

interface Animal {
    void Sound();
    void sleep();
}
class Dog implements Animal
{
    @Override
    public void Sound() {
        System.out.println("The Dog Sounds like : woof");
    }
 
    @Override
    public void sleep() {
        System.out.println("Dog Sleeping");
    }
}
public class interfaceDemo{
    public static void main(String args[]) {
        Dog o =new Dog();
        o.Sound();
        o.sleep();
    }
}
 

Output

The Dog Sounds like : woof
Dog Sleeping
To download raw file Click Here

Basic Programs