Simple understanding of Java abstract classes

In the top-down inheritance hierarchy, the classes at the upper level are more generic and may even be more abstract. From a certain point of view, the ancestor class is more general. It only contains some basic members. People only use it as the base class to derive other classes, not to create objects. Even, you can only give the definition of the method without implementation, and the subclass can implement it according to the specific requirements.

This method that only gives the method definition without concrete implementation is called abstract method. Abstract method has no method body, and there is no "{}" in the expression of code. A class containing one or more abstract methods must also be declared as an abstract class.

Use the abstract modifier to represent abstract methods and abstract classes.

In addition to abstract methods, abstract classes can also contain concrete variables and concrete methods. Even if a class does not contain abstract methods, it can be declared as an abstract class to prevent instantiation.

Abstract classes cannot be instantiated, and abstract methods must be implemented in subclasses. See the following code:

Operation results:

Some notes on abstract classes: abstract classes cannot be used directly. You must use subclasses to implement abstract classes, and then use instances of their subclasses. However, you can create a variable whose type is an abstract class and point it to an instance of a specific subclass, that is, you can use the abstract class as a formal parameter and the actual implementation class as an argument, that is, a polymorphic application. Cannot have abstract constructor or abstract static method.

A class will become an abstract class in the following cases: when one or more methods of a class are abstract methods; When a class is a subclass of an abstract class and cannot provide any implementation details or method body for any abstract method; When a class implements an interface and cannot provide implementation details or method bodies for any abstract methods; Note: what is said here is that a class will become an abstract class under these conditions. It is not said that an abstract class must have these conditions. A typical mistake: abstract classes must contain abstract methods. But on the contrary, "a class containing abstract methods must be an abstract class" is correct. In fact, an abstract class can be a completely normal implementation class

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>