Java - Interface versus Abstract Class

版权声明:欢迎转载并请注明出处,谢谢~~ https://blog.csdn.net/chimomo/article/details/53895005

Differences

  1. Methods of a Java interface are implicitly abstract and cannot have implementations. A Java abstract class can have instance methods that implements a default behaviour. In Java 8, you can have implementations on static and default methods in an interface.
  2. Variables declared in a Java interface are by default final. An abstract class may contain non-final variables.
  3. Members of a Java interface are public by default. A Java abstract class can have the usual flavours of class members like private, protected, etc.
  4. A Java interface should be implemented using keyword “implements”; A Java abstract class should be extended using keyword “extends”.
  5. An interface can extend another Java interface only, an abstract class can extend another Java class and implement multiple Java interfaces.
  6. A Java class can implement multiple interfaces but it can extend only one abstract class.
  7. Abstract classes have constructors, even though you cannot instantiate an abstract class, the constructor is used by child classes.
  8. Interfaces indicate "what" but not "how" because they define a contract (list of methods) while an abstract class can also indicate "how" (implement a method).
  9. Using interface you can have a base type for different families: Flyer f1=new Plane(); Flyer f2=new Bird(); Bird and Plane don't correspond to the same family but both can fly (are flyers).

When To Use Interfaces

An interface allows somebody to start from scratch to implement your interface or implement your interface in some other code whose original or primary purpose was quite different from your interface. To them, your interface is only incidental, something that have to add on to the their code to be able to use your package. The disadvantage is every method in the interface must be public. You might not want to expose everything.

When To Use Abstract classes

An abstract class, in contrast, provides more structure. It usually defines some default implementations and provides some tools useful for a full implementation. The catch is, code using it must use your class as the base. That may be highly inconvenient if the other programmers wanting to use your package have already developed their own class hierarchy independently. In Java, a class can inherit from only one base class.

When to Use Both

You can offer the best of both worlds, an interface and an abstract class. Implementors can ignore your abstract class if they choose. The only drawback of doing that is calling methods via their interface name is slightly slower than calling them via their abstract class name.

猜你喜欢

转载自blog.csdn.net/chimomo/article/details/53895005