A class containing the abstract modifier is an abstract class, and an abstract class cannot create instance objects. Classes containing abstract methods must be defined as abstract class, and methods in abstract class classes do not have to be abstract. Abstract methods defined in an abstract class must be implemented in a concrete subclass, so there cannot be abstract constructors or abstract static methods. If the subclass does not implement all abstract methods in the abstract parent class, then the subclass must also be defined as abstract type.
An interface can be said to be a special case of an abstract class, and all methods in the interface must be abstract. The method definitions in the interface default to public abstract type, and the member variable types in the interface default to public static final.
Let’s compare the grammatical differences between the two :
1. Abstract classes can have constructors, but interfaces cannot have constructors.
2. There can be ordinary member variables in abstract classes, but there are no ordinary member variables in interfaces.
3. Abstract classes can contain non-abstract ordinary methods. All methods in the interface must be abstract, and there cannot be non-abstract ordinary methods.
4. The access types of abstract methods in abstract classes can be public, protected and (default type, although
No error is reported under eclipse, but it should not work), but the abstract method in the interface can only be of public type, and the default is public abstract type.
5. Abstract classes can contain static methods, but interfaces cannot contain static methods.
6. Both abstract classes and interfaces can contain static member variables. The access type of static member variables in abstract classes can be arbitrary, but variables defined in interfaces can only be of public static final type, and the default is public static final type.
7. A class can implement multiple interfaces, but can only inherit one abstract class.
Let’s talk about the differences between the two in application :
Interfaces play more of a role in system architecture design methods and are mainly used to define communication contracts between modules. Abstract classes play a role in code implementation and can realize code reuse. For example, the template method design pattern is a typical application of abstract classes. It is assumed that all Servlet classes in a project must use the same method to determine permissions and record access. Log and handle exceptions, then you can define an abstract base class so that all Servlets inherit this abstract base class. In the service method of the abstract base class, permission judgment, access log recording and exception handling code are completed. The classes only complete their respective business logic codes. The pseudo code is as follows: