Interface vs. abstract class

Abstraction:

Hiding the internal implementation of the feature and only showing the functionality to the users. i.e. what it works (showing), how it works (hiding). Both abstract class and interface are used for abstraction.

Abstract class vs Interface

Type of methods: Interface can have only abstract methods. Abstract class can have abstract and non-abstract methods. From Java 8, it can have default and static methods also.
Final Variables: Variables declared in a Java interface are by default final. An abstract class may contain non-final variables.
Type of variables: Abstract class can have final, non-final, static and non-static variables. Interface has only static and final variables.
Implementation: Abstract class can provide the implementation of interface. Interface can’t provide the implementation of abstract class.
Inheritance vs Abstraction: A Java interface can be implemented using keyword “implements” and abstract class can be extended using keyword “extends”.
Multiple implementation: An interface can extend another Java interface only, an abstract class can extend another Java class and implement multiple Java interfaces.
Accessibility of Data Members: Members of a Java interface are public by default. A Java abstract class can have class members like private, protected, etc.

When to use what?

Consider using abstract classes if any of these statements apply to your situation:

  • In java application, there are some related classes that need to share some lines of code then you can put these lines of code within abstract class and this abstract class should be extended by all these related classes.
  • You can define non-static or non-final field(s) in abstract class, so that via a method you can access and modify the state of Object to which they belong.
  • You can expect that the classes that extend an abstract class have many common methods or fields, or require access modifiers other than public (such as protected and private).

Consider using interfaces if any of these statements apply to your situation:

  • It is total abstraction, All methods declared within an interface must be implemented by the class(es) that implements this interface.
  • A class can implement more than one interface. It is called multiple inheritance.
  • You want to specify the behavior of a particular data type, but not concerned about who implements its behavior.

具体而言,接口是公开的,里面不能有私有的方法或变量,是用于让别人使用的,而抽象类是可以有私有方法或私有变量的。如果一个类中包含抽象方法,那么这个类就是抽象类。通过把类或类中的某些方法声明位 abstract(abstract 只能用类修饰类或者方法,不能修饰属性)来表示一个类是抽象类。接口是指方法的集合,接口中所有的方法都没有方法体。
包含一个或多个抽象方法的类就必须被声明为抽象类,抽象类可以声明 方法的存在而不去实现它,被声明为抽象的方法不能包含方法体。在抽象类的子类中,实现方法必须含有相同的或更低的访问级别(public > protected > private)。抽象类在使用的过程中不能被实例化,但是可以创建一个对象使其指向具体子类的一个实例。

你可能感兴趣的:(Interface vs. abstract class)