Detailed explanation of Java abstract class definition and method instance

In the object-oriented concept, all objects are described by classes, but conversely, not all classes are used to describe objects. If a class does not contain enough information to describe a specific object, such a class is an abstract class.

Except that an abstract class cannot instantiate an object, other functions of the class still exist. The access methods of member variables, member methods and constructor methods are the same as those of ordinary classes.

Because abstract classes cannot instantiate objects, they must be inherited before they can be used. For this reason, it is usually decided whether to design abstract classes at the design stage.

The parent class contains common methods for the collection of subclasses, but these methods cannot be used because the parent class itself is abstract.

abstract class

Abstract classes are used in the Java language to define abstract classes. Examples are as follows:

Note that the Employee class is no different. Although it is an abstract class, it still has three member variables, seven member methods and one constructor. Now, if you try the following example:

When you try to compile the abstractdemo class, the following error occurs:

Inherit abstract classes

We can inherit the Employee class through general methods:

Although we cannot instantiate an employee class object, if we instantiate a salary class object, the object will inherit 3 member variables and 7 member methods from the Employee class.

The compilation and operation results of the above program are as follows:

Abstract method

If you want to design a class that contains a special member method, and the specific implementation of the method is determined by its subclass, you can declare the method as an abstract method in the parent class.

Abstract keyword can also be used to declare abstract methods. Abstract methods contain only one method name and no method body.

The abstract method is undefined. The method name is directly followed by a semicolon instead of curly braces.

Declaring abstract methods results in the following two results:

If a class contains abstract methods, the class must be abstract.

Any subclass must override the abstract method of the parent class or declare itself an abstract class.

Subclasses that inherit abstract methods must overload the method. Otherwise, the subclass must also be declared as an abstract class. Finally, a subclass must implement the abstract method, otherwise, from the initial parent class to the final subclass can not be used to instantiate the object.

If the salary class inherits the Employee class, it must implement the computepay() method:

I hope this article can help friends in need

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
分享
二维码
< <上一篇
下一篇>>