Java abstract class versus interface

  • 2020-05-26 09:13:29
  • OfStack

Java abstract class versus interface

preface

abstract class and interface are both used by Java to describe abstract objects. I wonder if anyone has any doubts like me about the grammatical differences between abstract class and interface and how to choose them. Anyway, let me introduce abstract class and interface in detail.

Understanding abstract classes

In the object-oriented concept, all objects are described by classes. But the opposite is not true, and not all classes are used to describe objects. Because there may not be enough information in this class to describe a concrete object, such a class is an abstract class (ps: note that the abstract class does not refer to abstract class). Abstract classes are often used to describe the abstract concepts that we derive from analyzing and designing the problem domain. They are abstractions of concrete concepts that look different but are essentially the same in series 1.

The difference between abstract class and interface grammar

The differences between abstract classes and interfaces are as follows:

Abstract classes can have normal member variables, whereas interfaces generally have no member variables. If a member variable is to be inserted into an interface, the type of the member variable must be of type static final. Abstract classes can contain non-abstract ordinary methods, and all methods in an interface must be abstract. The access type for an abstract method in an abstract class can be public, protected, or package access type. The abstract methods in the interface can only be of type public abstract. The interface methods can be unmodified and the default is type public abstract. One class can implement multiple interfaces (a compromise implementation of multiple inheritance), but only one abstract class can be inherited.

The difference between the use of abstract class and interface

The design of abstract class embodies the relationship of "is-a", while interface embodies the relationship of "has-a".

When to use the interface?

If you want to extend what I give you, you must implement the necessary interfaces. For example, objects that implement the Comparable interface can be ordered directly using the sort method Collections.sort (List list).

When do you use abstract classes?

If you have an abstract class, it provides a lot of common functionality and abstracts out the methods that each subclass needs to implement itself. If you design something based on that class, then the implementation can inherit the abstract class and implement its own unique methods.

Thank you for reading, I hope to help you, thank you for your support of this site!


Related articles: