Differences between abstract classes and interfaces in Java
There are many similarities and similarities between interfaces and abstract classes. Many people have the following question: why is it necessary to use interfaces instead of abstract classes in some places, and abstract classes instead of interfaces in other places? In other words, when considering the generalization of Java classes, many may hesitate between interfaces and abstract classes, or even choose either.
Understanding abstract classes
Abstract class and interface are used for abstract classes in Java language (abstract classes in this article are not translated from abstract class, it represents an abstract body, abstract class is a method used to define abstract classes in the Java language. Please note that it is defined). So what is an abstract class and what benefits can it bring to us by using abstract classes?
Abstract class: an abstract class is a special base class. In addition to some basic attributes and methods, it can also contain methods that are declared but not implemented. abstract is used to declare
For example:
Interface: an interface is a more abstract type. All the methods declared in the interface are disclosed to the implementer for implementation.
In summary, we can see the main differences between abstract classes and interfaces:
1. abstract classes can have their own methods, but the methods of interfaces are only declared.
2. abstract methods of abstract classes are declared using abstract statements.
Note the following:
1. A class can only inherit one implementation class, but multiple interfaces can be implemented.
2. When an abstract class and an interface have common attributes, compilation fails if a class implements this abstract class and interface at the same time.
Interface:
A highly abstract class that is declared using the interface keyword.
The following defines a Usb interface:
Public interface Usb {
Public void start ();
Public void end ();
}
No constructor IN THE INTERFACE
Interfaces are the same as abstract classes and cannot be instantiated.
Variables cannot be defined in interfaces, methods cannot have method bodies, methods are public by default, and methods in Chinese and abstract methods cannot be modified in private.
Only interfaces can be inherited. Multiple inheritance is supported (interfaces are separated by commas)
Class implementation interface, using the keyword implements:
1. All methods of this interface must be implemented unless the implementation class is an abstract class.
2. One class can implement multiple interfaces