A Guide to Instantiation and Practice of Java Generic Abstract Classes

This article takes an in-depth look at the common problems when using generic abstract classes in Java that cannot be directly instantiated due to their abstract nature. We will explain the concept of abstract classes in detail and guide developers on how to correctly instantiate and use such generic classes through various solutions, including anonymous inner classes, removing abstract modifiers, and creating concrete subclasses. We especially recommend creating concrete subclasses to achieve modularity and reusability.
Understanding Java abstract classes and their instantiation limitations
In Java, abstract keyword is used to declare abstract classes or abstract methods. An abstract class is a class that cannot be directly instantiated. It usually contains one or more abstract methods (methods without concrete implementation), or serves as a skeleton class that is intended to be inherited and improved by subclasses. Its core purpose is to provide a common base class structure that forces or recommends subclasses to implement certain behaviors.
When trying to directly instantiate an abstract class, the Java compiler will throw errors such as "Cannot instantiate the type AbstractMiniMap". This is precisely because the abstract class itself is incomplete and requires its concrete subclasses to provide the implementation of all abstract methods.
Consider the following definition of the generic abstract class AbstractMiniMap:
public abstract class AbstractMiniMap<k v> implements MiniMap<k v> {
// ...class members and methods...
public AbstractMiniMap() {
this.size = 0;
this.keys = new Object[CAPACITY];
this.vals = new Object[CAPACITY];
}
// ...other methods...
}</k></k>
And the error when trying to instantiate in the main method:
public static void main(String[] args) {
// Error: Unable to instantiate abstract class AbstractMiniMap
AbstractMiniMap<double double> asd = new AbstractMiniMap(20,30);
}</double>
The problem here is that AbstractMiniMap is declared abstract, so its instance cannot be created directly using the new keyword. Even if it has no abstract methods, as long as it is marked abstract, it cannot be instantiated directly.
solution
For the instantiation restrictions of abstract classes, there are several common solutions:
1. Use anonymous inner class instantiation
In some specific scenarios, if the abstract class does not have abstract methods, or you only need a temporary, one-time instance to override or implement certain behaviors, you can use anonymous inner classes for instantiation.
Sample code:
public static void main(String[] args) {
// Instantiate AbstractMiniMap using anonymous inner class
// Note: AbstractMiniMap has no abstract methods, so you can use empty curly braces directly here. AbstractMiniMap<double double> map = new AbstractMiniMap<double double>() {
// If AbstractMiniMap has abstract methods, they must be implemented here // For example:
// @Override
// public void push(Double key, Double value) { /* Implementation*/ }
// @Override
// public Double remove(Double key) { /* implementation*/ }
};
System.out.println("Capacity of anonymous inner class instantiation: " map.capacity());
}</double></double>
Things to note:
- This method is suitable for situations where there are no abstract methods in the abstract class, or when all abstract methods can be implemented concisely in anonymous inner classes.
- Anonymous inner classes are usually used to create one-time-use objects and are not suitable for scenarios that require multiple reuse or complex logic.
- If an abstract class contains abstract methods, you must provide concrete implementations of these methods in an anonymous inner class.
2. Remove abstract modifier (modify class definition)
If your design intention is to make AbstractMiniMap a concrete class that can be used directly, and it does not itself contain any unimplemented abstract methods, then the most straightforward way is to remove the abstract keyword from the class declaration.
Modified class definition:
// Remove the abstract keyword public class MiniMapImpl<k v> implements MiniMap<k v> { // It is recommended to modify the class name at the same time to comply with the naming convention // ... Class members and methods...
public MiniMapImpl() {
this.size = 0;
this.keys = new Object[CAPACITY];
this.vals = new Object[CAPACITY];
}
// Must implement all abstract methods of the MiniMap interface, such as push and remove
// For example:
// @Override
// public void push(K key, V value) { /* Implementation*/ }
// @Override
// public V remove(K key) { /* implementation*/ }
}</k></k>
Instantiation method:
public static void main(String[] args) {
// Directly instantiate the modified concrete class MiniMapImpl<double double> map = new MiniMapImpl();
System.out.println("Capacity of concrete class instantiation: " map.capacity());
}</double>
Things to note:
- This approach changes the original design intent of the class. If AbstractMiniMap is designed to serve as a base class for other concrete implementations, abstract should not be easily removed.
- After removing abstract, the class must implement all abstract methods in its interface (MiniMap), otherwise it will itself need to be declared as an abstract class.
- Following Java naming conventions, change the class name from AbstractMiniMap to something more descriptive, such as MiniMapImpl or SimpleMiniMap.
3. Create specific subcategories (recommended solution)
This is the solution that best adheres to object-oriented design principles. If AbstractMiniMap is designed as an abstract skeleton, then its concrete subclasses should be created to provide a complete implementation.
Solution 1: Create a specific subclass of a specific type
If in your application scenario, MiniMap always handles a specific type (such as Double), you can create a specialized subclass.
//Define a specific subclass that inherits AbstractMiniMap
public class DoubleMiniMap extends AbstractMiniMap<double double> {
// The constructor can call the parent class constructor public DoubleMiniMap() {
super(); // Call the no-argument constructor of AbstractMiniMap}
// Must implement all abstract methods in the MiniMap interface that are not implemented by AbstractMiniMap // For example, assume that the MiniMap interface defines the push and remove methods @Override
public void push(Double key, Double value) {
// Specific implementation if (size <p> <strong>Instantiation method:</strong></p>
<pre class="brush:php;toolbar:false"> public static void main(String[] args) {
// Instantiate the specific subclass DoubleMiniMap map = new DoubleMiniMap();
map.push(10.0, 20.0);
map.push(30.0, 40.0);
System.out.println("DoubleMiniMap instance: " map.toString());
System.out.println("Capacity: " map.capacity() ", Size: " map.size());
}
Option 2: Create a generic concrete subclass
If you want your subclass to remain generic to support different types of key-value pairs, you can create a concrete subclass of the generic.
//Define a generic concrete subclass and inherit AbstractMiniMap
public class GenericMiniMap<k v> extends AbstractMiniMap<k v> {
public GenericMiniMap() {
super();
}
//Similarly, all abstract methods not implemented by AbstractMiniMap in the MiniMap interface must be implemented @Override
public void push(K key, V value) {
// Generic implementation if (size <p> <strong>Instantiation method:</strong></p>
<pre class="brush:php;toolbar:false"> public static void main(String[] args) {
// Instantiate the generic concrete subclass GenericMiniMap<double double> map1 = new GenericMiniMap();
map1.push(1.0, 2.0);
map1.push(3.0, 4.0);
System.out.println("GenericMiniMap<double double> instance: " map1.toString());
GenericMiniMap<string integer> map2 = new GenericMiniMap();
map2.push("Apple", 10);
map2.push("Banana", 20);
System.out.println("GenericMiniMap<string integer> Example: " map2.toString());
}</string></string></double></double>
Things to note:
- This is the most recommended way. It follows the design intention of abstract classes, placing general logic in abstract classes and leaving specific implementation to subclasses.
- Subclasses must implement all unimplemented abstract methods in the abstract class and all unimplemented abstract methods in its interface.
- By creating specific subclasses, code modularity and reusability can be achieved, and different subclasses can provide different implementation strategies.
Summarize
The core of dealing with the instantiation of generic abstract classes in Java is to understand the characteristics of abstract classes - they cannot be instantiated directly. The choice of solution depends on your design intent and specific needs:
- Anonymous inner class : suitable for fast, one-time use, and the abstract class does not contain abstract methods or the abstract methods are simple to implement.
- Remove the abstract keyword : If the class should be a concrete class and not used as a base class for other implementations, you can consider removing it, but make sure to implement all interface methods and follow naming conventions.
- Create concrete subclasses (recommended) : This is the approach that is most consistent with object-oriented principles. It allows abstract classes to serve as skeletons, and concrete subclasses provide complete implementations to achieve good structure and scalability of code.
In most professional development scenarios, extending an abstract class by creating concrete subclasses is the preferred option because it provides a clear inheritance structure and a high degree of flexibility.
The above is the detailed content of A Guide to Instantiation and Practice of Java Generic 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
AI Clothes Remover
Online AI tool for removing clothes from photos.
Undresser.AI Undress
AI-powered app for creating realistic nude photos
ArtGPT
AI image generator for creative art from text prompts.
Stock Market GPT
AI powered investment research for smarter decisions
Hot Article
Popular tool
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)
Hot Topics
20518
7
13631
4
How to configure Spark distributed computing environment in Java_Java big data processing
Mar 09, 2026 pm 08:45 PM
Spark cannot run in local mode, ClassNotFoundException: org.apache.spark.sql.SparkSession. This is the most common first step of getting stuck: even the dependencies are not correct. Only spark-core_2.12 is written in Maven, but spark-sql_2.12 is not added. SparkSession crashes as soon as it is built. The Scala version must strictly match the official Spark compiled version - Spark3.4.x uses Scala2.12 by default. If you use spark-sqljar of 2.13, the class loader cannot directly find the main class. Practical advice: Go to mvnre
How to safely map user-entered weekday string to integer value and implement date offset operation in Java
Mar 09, 2026 pm 09:43 PM
This article introduces a concise and maintainable way to map the weekday string (such as "Monday") to the corresponding serial number (1-7), and use the modulo operation to realize the forward and backward offset of any number of days (such as Monday plus 4 days to get Friday), avoiding lengthy if chains and hard-coded logic.
How to generate a list of duplicate elements using Java's Collections.nCopies_Initialization tips
Mar 06, 2026 am 06:24 AM
Collections.nCopies returns an immutable view. Calling add/remove will throw UnsupportedOperationException; it needs to be wrapped with newArrayList() to modify it, and it is disabled for mutable objects.
How to use Homebrew to install Java on Mac_A must-have Java tool chain for developers
Mar 09, 2026 pm 09:48 PM
Homebrew installs the latest stable version of openjdk (such as JDK22) by default, not the LTS version; you need to explicitly execute brewinstallopenjdk@17 or brewinstallopenjdk@21 to install the LTS version, and manually configure PATH and JAVA_HOME to be correctly recognized by the system and IDE.
What is exception masking (Suppressed Exceptions) in Java_Multiple resource shutdown exception handling
Mar 10, 2026 pm 06:57 PM
What is SuppressedException: It is not "swallowed", but actively archived by the JVM. SuppressedException is not an exception loss, but the JVM quietly attaches the secondary exception to the main exception under the premise that "only one exception must be thrown" for you to verify afterwards. It is automatically triggered by the JVM in only two scenarios: one is that the resource closure in try-with-resources fails, and the other is that you manually call addSuppressed() in finally. The key difference is: the former is fully automatic and safe; the latter requires you to keep it to yourself, and it can be written as shadowing if you are not careful. try-
How to correctly implement runtime file writing in Java applications (avoiding JAR internal write failures)
Mar 09, 2026 pm 07:57 PM
After a Java application is packaged as a JAR, data cannot be written directly to the resources in the JAR package (such as test.txt) because the JAR is essentially a read-only ZIP archive; the correct approach is to write variable data to an external path (such as a user directory, a temporary directory, or a configuration-specified path).
What is the underlying principle of array expansion in Java_Java memory dynamic adjustment analysis
Mar 09, 2026 pm 09:45 PM
ArrayList.add() triggers expansion because grow() is called when size is equal to elementData.length. The first add allocates 10 capacity, and subsequent expansion is 1.5 times and not less than the minimum requirement, relying on delayed initialization and System.arraycopy optimization.
How to safely read a line of integer input in Java and avoid Scanner blocking
Mar 06, 2026 am 06:21 AM
This article introduces typical blocking problems when using Scanner to read multiple integers in a single line. It points out that hasNextInt() will wait indefinitely when there is no subsequent input, and recommends a safe alternative with nextLine() string splitting as the core.





