Abstract classes are used to capture the common characteristics of subclasses and are used to create templates for subclasses in the inheritance hierarchy. In reality, there is really no need to write some methods in the parent class, because the method in each subclass will definitely be different; instead, write it as an abstract class, so that when you look at the code, you will know that this is an abstract method, and you will know that this method is in the subclass. It is implemented in the class, so it has a prompt effect.
1. What is an abstract class
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 abstract classes cannot instantiate objects, other functions of the class still exist. Member variables, member methods and constructors can be accessed in the same way as ordinary classes.
Since abstract classes cannot instantiate objects, abstract classes must be inherited before they can be used. For this reason, it is usually decided during the design stage whether to design an abstract class.
The parent class contains common methods of the subclass collection, but because the parent class itself is abstract, these methods cannot be used.
In Java, abstract classes represent an inheritance relationship. A class can only inherit one abstract class, but a class can implement multiple interfaces.
2. Why use abstract classes? What is the use of abstract classes?
I always wonder why we need to reference abstract classes. Aren’t ordinary classes enough? Methods defined in general classes can also be overridden by subclasses. There is no need to define them as abstract.
In fact, this is not to say that abstract classes are of any use. General classes can indeed satisfy applications. However, in reality, there are indeed some methods in parent classes that are not necessary to write, because the methods in each subclass will definitely be different. , so there is no need to write it in the parent class. Of course, you can also write all abstract classes as non-abstract classes, but this is not necessary.
And write it as an abstract class, so that when others see your code, or you see other people's code, you will pay attention to the abstract method and know that this method is implemented in the subclass, so there is Prompt function.
3. The difference between abstract classes and interfaces
Abstract classes
Abstract classes are used To capture the common characteristics of subclasses. It cannot be instantiated and can only be used as a superclass for subclasses. Abstract classes are templates used to create subclasses in the inheritance hierarchy.
Interface
An interface is a collection of abstract methods. If a class implements an interface, then it inherits the abstract methods of this interface. This is like the contract pattern, if you implement this interface, then you must ensure that these methods are used. An interface is just a form, it can't do anything by itself.
Comparison of abstract classes and interfaces
When to use abstract classes and interfaces
- If you have some methods and want some of them to have default implementations, then use an abstract class.
- If you want to implement multiple inheritance, then you must use interfaces. Since Java does not support multiple inheritance, subclasses cannot inherit multiple classes, but they can implement multiple interfaces. So you can use interfaces to solve it.
- If the basic functionality is constantly changing, then you need to use abstract classes. If you keep changing the basic functionality and use an interface, you will need to change all classes that implement the interface.
- If there is an interface and five implementation classes, the current requirement may be to add a method to the interface, which will require changing the five implementation classes, but the requirement only needs to change two of the implementation classes, which can be defined again An abstract class implements this interface, adds this method in the abstract class, and then the other two implementation classes implement this abstract class, or uses the new features in Java 8 to add default methods or static methods in the interface .
For more programming-related knowledge, please visit: Programming Learning! !
The above is the detailed content of What is the role of abstract classes?. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

The settings.json file is located in the user-level or workspace-level path and is used to customize VSCode settings. 1. User-level path: Windows is C:\Users\\AppData\Roaming\Code\User\settings.json, macOS is /Users//Library/ApplicationSupport/Code/User/settings.json, Linux is /home//.config/Code/User/settings.json; 2. Workspace-level path: .vscode/settings in the project root directory

To correctly handle JDBC transactions, you must first turn off the automatic commit mode, then perform multiple operations, and finally commit or rollback according to the results; 1. Call conn.setAutoCommit(false) to start the transaction; 2. Execute multiple SQL operations, such as INSERT and UPDATE; 3. Call conn.commit() if all operations are successful, and call conn.rollback() if an exception occurs to ensure data consistency; at the same time, try-with-resources should be used to manage resources, properly handle exceptions and close connections to avoid connection leakage; in addition, it is recommended to use connection pools and set save points to achieve partial rollback, and keep transactions as short as possible to improve performance.

itertools.combinations is used to generate all non-repetitive combinations (order irrelevant) that selects a specified number of elements from the iterable object. Its usage includes: 1. Select 2 element combinations from the list, such as ('A','B'), ('A','C'), etc., to avoid repeated order; 2. Take 3 character combinations of strings, such as "abc" and "abd", which are suitable for subsequence generation; 3. Find the combinations where the sum of two numbers is equal to the target value, such as 1 5=6, simplify the double loop logic; the difference between combinations and arrangement lies in whether the order is important, combinations regard AB and BA as the same, while permutations are regarded as different;

DependencyInjection(DI)isadesignpatternwhereobjectsreceivedependenciesexternally,promotingloosecouplingandeasiertestingthroughconstructor,setter,orfieldinjection.2.SpringFrameworkusesannotationslike@Component,@Service,and@AutowiredwithJava-basedconfi

fixture is a function used to provide preset environment or data for tests. 1. Use the @pytest.fixture decorator to define fixture; 2. Inject fixture in parameter form in the test function; 3. Execute setup before yield, and then teardown; 4. Control scope through scope parameters, such as function, module, etc.; 5. Place the shared fixture in conftest.py to achieve cross-file sharing, thereby improving the maintainability and reusability of tests.

java.lang.OutOfMemoryError: Javaheapspace indicates insufficient heap memory, and needs to check the processing of large objects, memory leaks and heap settings, and locate and optimize the code through the heap dump analysis tool; 2. Metaspace errors are common in dynamic class generation or hot deployment due to excessive class metadata, and MaxMetaspaceSize should be restricted and class loading should be optimized; 3. Unabletocreatenewnativethread due to exhausting system thread resources, it is necessary to check the number of threads, use thread pools, and adjust the stack size; 4. GCoverheadlimitexceeded means that GC is frequent but has less recycling, and GC logs should be analyzed and optimized.

Use classes in the java.time package to replace the old Date and Calendar classes; 2. Get the current date and time through LocalDate, LocalDateTime and LocalTime; 3. Create a specific date and time using the of() method; 4. Use the plus/minus method to immutably increase and decrease the time; 5. Use ZonedDateTime and ZoneId to process the time zone; 6. Format and parse date strings through DateTimeFormatter; 7. Use Instant to be compatible with the old date types when necessary; date processing in modern Java should give priority to using java.timeAPI, which provides clear, immutable and linear

The core of mastering Advanced SpringDataJPA is to select the appropriate data access method based on the scenario and ensure performance and maintainability. 1. In custom query, @Query supports JPQL and native SQL, which is suitable for complex association and aggregation operations. It is recommended to use DTO or interface projection to perform type-safe mapping to avoid maintenance problems caused by using Object[]. 2. The paging operation needs to be implemented in combination with Pageable, but beware of N 1 query problems. You can preload the associated data through JOINFETCH or use projection to reduce entity loading, thereby improving performance. 3. For multi-condition dynamic queries, JpaSpecifica should be used
