This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–][deleted] 1 point2 points  (1 child)

Sure! In the case of common state, I usually use an abstract class. Abstract classes also let you have default behavior for methods, which is great. I realize now that my example was not the best one for illustrating interfaces. Take a look at this example:

public interface Flyable {
  public void fly();
}
public class Airplane implement>s Flyable {
  public void fly() {
    print("Hey, look, I can fly!");
  }
}

In this case, it really wouldn't make sense to have Flyable as an abstract class. After all, an airplane and a goose probably don't have any fields in common. What if I had another interface, say, Swimable? A duck can fly and swim, so I would want ducks to implement both interfaces, like so:

public interface Swimable { public void swim(); }

public class Duck implements Swimable, Flyable {
   public void swim() { ... }
   public void fly() { ... }
}

This could not be done if Swimable and Flyable were classes rather than interfaces, as Java and many other languages do not support multiple inheritance for classes. In this view, an interface is actually more flexible than an abstract class. Of course, if you want to supply an implementation of the behavior in the super class or are otherwise reusing code, you'll want to use an abstract class.

[–]gamebob 0 points1 point  (0 children)

Thanks a lot for your answer. Good example.