Reputation: 27
I was recently introduced to interfaces in Java, but I'm having trouble understanding their purpose. So, let's say I have the following:
//this is an interface
public interface DanceMoves {
public void theJitterbug(int twists);
public void theHustle(int steps);
public void theMoonwalk(int slides);
}
And then I have a class that implements this interface:
public class DanceClub implements DanceMoves {
public void theJitterbug(int twists) {
System.out.println("Twist " + twists + " times!");
}
public void theHustle(int steps) {
System.out.println("Step " + steps + " times!");
}
public void theMoonwalk(int slides) {
System.out.println("Slide " + slides + " times!");
}
//more methods can go here
public static void main(String[] args) {
DanceClub letsDance = new DanceClub();
letsDance.theJitterbug(5);
letsDance.theHustle(4);
letsDance.theMoonwalk(3);
}
}
And perhaps I have another method that implements this interface:
public class Diner implements DanceMoves {
public void theJitterbug(int twists) {
System.out.println("Twist " + twists + " times!");
System.out.println("We only do the jitterbug in diners!");
}
public void theHustle(int steps) {
}
public void theMoonwalk(int slides) {
}
public static void main(String[] args) {
Diner letsDanceAgain = new Diner();
letsDanceAgain.theJitterbug(5);
}
}
So my question is, why do we bother implementing an interface if we have to rewrite all of the interface methods anyways? How is this reusing code?
EDIT: Thanks a bunch to all who answered! I am new to Java, and the only other language I've learned so far is Jython. So while a lot of the concepts translate over quite nicely, some of the newer things are a bit harder for me to grasp.
I also appreciated the response example given below, as well as those links to previous questions and outside sources. I had actually read through most of those questions earlier and had been to those outside sources, but they were more helpful after I was able to develop a clearer understanding of what I was actually reading!
But anyways! What I really wanted to do was write down my big takeaway (for both my sake and the sake of posterity) about interfaces, and see if I really do "get it". My previous questions were, why do we bother implementing an interface if we have to rewrite all of the interface methods anyways? How is this reusing code?. Using Elliot Frisch's revision of my example:
public interface Dance { //an interface
public void boogie(int count);
}
Now, you could have methods, related or not, that implement this interface -
public class theMoonwalk implements Dance {
public void boogie(int count) {
System.out.println("Slide " + count + " times!");
}
public void mJ() {
System.out.println("Michael Jackson did this dance!");
}
public class theHustle implements Dance {
public void boogie(int steps) {
System.out.println("Step " + steps + " times!");
}
}
public class theJitterBug implements Dance {
public void boogie(int twists) {
System.out.println("Twist " + twists + " times!");
}
}
public class crazyUncle implements Dance {
public void boogie(int shimmy) {
System.out.println("I really don't know how to dance.");
}
public void yap() {
System.out.println("When I was your age...!");
}
}
Then to use it,
public static void main(String[] args) {
Dance[] dances = new Dance[] {
new theHustle(), new theMoonwalk(), new theJitterBug(), new crazyUncle()
};
for (Dance d : dances) { //for each element in this array of type Dance...
// Note: The caller just boogies. The object determines the "move".
d.boogie(3);
}
}
Now, here is my explanation for why I should bother implementing an interface if I have to rewrite all of the interface methods anyways:
Because the theHustle, theMoonwalk, theJitterbug and crazyUncle classes each implement the Dance interface, they've, in effect, "signed" a "contract" that guarantees that instances of these classes will, at minimum, contain the methods from the Dance interface. Thus, even though, for example, the theMoonwalk class is different from the crazyUncle class, theMoonwalk objects and crazyUncle objects can, for example, be included in an array of type Dance, because those objects contain the "DNA" of the Dance interface.
Further, I could have another method in a different class that takes in a parameter of type Dance:
public void danceExercise(Dance d, int num) {
d.boogie(num);
}
When calling the danceExercise method, for the Dance d parameter, I can provide any value that is of a type that implements the Dance interface. So, since crazyUncle and theMoonwalk both implement Dance, I can provide an instance of crazyUncle or an instance of theMoonwalk where a Dance is expected.
TL;DR Thanks all! I now have a sharper understanding of interfaces.
Upvotes: 1
Views: 282
Reputation: 81307
Inheritance in Java encompasses two concepts. If X inherits from Y, that means...
X is substitutable for Y, meaning that a reference to X may be used anyplace a reference to a Y is required.
An instance of X may use members of an inherited Y members as its own.
The Java runtime only allows a class to use members inherited from one other type as though they were its own. Consequently, a class may inherit from only one other class. On the other hand, there is no reason why a class should not be able to play many different rules, being substitutable for many different unrelated things.
Interfaces allow a means of defining substitution classes, such that code demanding something which implements a particular interface will be able to accept a reference to an object of any type which implements that interface. Because a class which implements an interface has historically been required to implement all of the interface members itself, classes implementing interfaces didn't inherit anything from those interfaces beyond the ability to be passed to code expecting the interface types, and thus the runtime limitations on single inheritance pose no impediment to classes implementing multiple interfaces.
Upvotes: 0
Reputation: 7287
my favorite question to ask for interview
https://en.wikipedia.org/wiki/Strategy_pattern
If you get the strategy pattern, then you would be able to explain others as well
Upvotes: 0
Reputation: 730
An interface allows a method to be confident that what you are passing into it is compatible. It allows you to therefore write code like this:
interface Animal
{
public String getSound();
}
and have two classes Cat
and lizard
that implement this interface, they will each then define what the method getSound()
does. Therefore say you have a method like this:
public void makeSound(Animal animal) { /*make the sound, using animal.getSound()*/}
The method can be sure that any classes that implement Animal
must have a defined sound as that is an attribute of Animal
, so it is safe to pass in Lizard
or Cat
in as they implement Animal
. This saves you from making makeSound(Cat cat)
and makeSound(Lizard lizard)
.
This means you are reusing code, just different code (the makeSound()
method only has to be defined once!). Just imagine it is a form of contract, that ensures that an Object is compatible with a method
Upvotes: 0
Reputation: 201527
Your question actually encapsulates a perfect example of why interfaces are useful - but lets "tap" around to the point,
public void theJitterbug(int twists) {
System.out.println("Twist " + twists + " times!");
}
public void theHustle(int steps) {
System.out.println("Step " + steps + " times!");
}
public void theMoonwalk(int slides) {
System.out.println("Slide " + slides + " times!");
}
Are all dances! So, let's call them like that...
public interface Dance {
public void getDown(int count);
}
Now, you could have -
public class TheMoonwalk implements Dance {
public void getDown(int count) {
System.out.println("Slide " + count + " times!");
}
}
public class TheHustle implements Dance {
public void getDown(int steps) {
System.out.println("Step " + steps + " times!");
}
}
public class TheJitterBug implements Dance {
public void getDown(int twists) {
System.out.println("Twist " + twists + " times!");
}
}
And then to use it,
public static void main(String[] args) {
Dance[] dances = new Dance[] {
new TheHustle(), new TheMoonwalk(), new TheJitterBug()
};
for (Dance d : dances) {
// Note: The caller just gets down. The object determines the "move".
d.getDown(3);
}
}
Upvotes: 1
Reputation: 4400
There is a lot of info on the topic as pointed out by rahul pasrich and ra2085. To more directly answer your question, it's so you can do things like take an argument of type DanceMoves and not care where it was implemented. You may have 6 different types of dance moves, and a single Avatar object your sending them to. This is one of the key concepts of Polymorphism.
Upvotes: 0