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.
In this program, we have an interface named Animal which has two abstract methods named Sound() and sleep(). The Animal interface defines what methods should be implemented by any class that implements the Animal interface.
Then, we have a class named Dog that implements the Animal interface. It provides implementation for both the Sound() and sleep() methods defined in the Animal interface.
Finally, we have the interfaceDemo class which creates an object of Dog and calls the Sound() and sleep() methods on it. The output of the program is the dog sound "woof" and a message indicating that the dog is sleeping.
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(); } }
The Dog Sounds like : woof Dog SleepingTo download raw file Click Here
Learn All in Tamil © Designed & Developed By Tutor Joes | Privacy Policy | Terms & Conditions