Best Example of Java Interface,Java Interface Tutorial,Core Java

To those who are having a hard time understanding the concept of an interface, I'll try my best to explain, but remember that I too am still a learner of Java (though I'm reasonably familiar with several other object-oriented languages). Let's say you're defining several different animals as their own classes. There are certain things that you are going to expect all of these classes to do: you are going to expect them to have a method of eating, of pooping, of drinking, of walking, and so on. These are all methods that you would define in the class definitions of each animal. 

You would therefore create an interface, called Animal: 

interface Animal { 
void eat(String food); 
void makeBowelMovement(int number); 
void drink(String liquid); 
void walk(int distance); } 
Notice that none of these methods are defined here. We are just defining the interface to an animal (the programming interface to an object of a class that implements the Animal interface). Now let's write an example class that implements this interface; say, Dog: 
class Dog implements Animal { 
void eat(String food) { System.out.println("I am now eating " + food); } 
void makeBowelMovement(int number) { 
if (number == 1) { System.out.println("I am now seeing."); } 
else if (number == 2) { System.out.println("I am now tired."); } 

void drink(String liquid) { System.out.println("I am now drinking " + liquid); } 
void walk(int distance) { System.out.println("I walked " + distance + " spots."); } 

Does it make more sense now? The explanation given in the tutorial is a little off, in my opinion; an interface in Java is not really about presenting a way of interacting with an object -- that's the job of the methods of the class itself. The point of a class implementing an interface is to make it known to yourself and other programmers that this class is going to act in a predictable way. All other classes that "implement Animal", in the example above, would have to offer the same methods. That way, you don't have to know how exactly each animal goes about, say, pooping. You only need to know that the Animal interface requires an implementing class to offer a void makeBowelMovement(int number) method.

No comments:

Post a Comment

Please Provide your feedback here