Abstract Class & Method
About
An abstract class in Java is a class that cannot be instantiated directly, meaning we cannot create objects of an abstract class using the new keyword. Instead, it serves as a blueprint for other classes and may contain both abstract and concrete methods.
Thread is not a abstract class.
Opposite of Abstract class is concrete class.
Abstract class supports multilevel inheritance. Note that Java does not support multiple inheritance with classes, but it supports multilevel inheritance.
Partial Implementation: Abstract classes allow partial implementation, where a class can have both abstract (unimplemented) and concrete (implemented) methods. This flexibility provide default behaviors while enforcing that subclasses implement specific methods.
Abstract Keyword
An abstract class or method is declared using the abstract keyword before the class name.
// Abstract class
public abstract class Shape {
// Abstract method
public abstract double area();
// Concrete method
public void display() {
System.out.println("This is a shape.");
}
}Abstract Methods
Abstract methods are method declarations that don't have a body (implementation). They are declared using the abstract keyword before the method return type. Subclasses that inherit/extends from the abstract class must provide implementations for all inherited abstract methods. Abstract methods define the functionality that subclasses must adhere to, promoting a common interface within the class hierarchy.
Non-Abstract Methods
Abstract classes can also have concrete methods (methods with a body) that provide default implementations for common functionalities. Subclasses can inherit and potentially override these methods to customize behavior.
Instantiation
We cannot create objects directly from an abstract class using the new keyword. Subclasses, which are not abstract, can be instantiated.
Access Modifier
Access Modifiers control the visibility and accessibility of classes, methods, and fields. Abstract classes leverage access modifiers to encapsulate certain methods or fields, making them accessible only to specific parts of the program. This capability is useful in complex hierarchies where we want to limit access to certain parts of the abstract class.
1. public Modifier
public ModifierAbstract classes and methods can use the public modifier to allow maximum visibility. For example, if an abstract method needs to be implemented across packages, it should be declared public in the abstract class.
2. protected Modifier
protected Modifierprotected methods in an abstract class can only be accessed within the same package or by subclasses in other packages. This is useful for methods that should only be available to subclasses but hidden from other classes.
3. default (Package-Private) Modifier
default (Package-Private) ModifierThe package-private (default) modifier restricts visibility to within the same package. In an abstract class, a method declared with no access modifier can only be accessed by classes within the same package.
4. private Modifier
private ModifierIn Java, private is not allowed for methods declared in an abstract class because it would make them inaccessible to subclasses. However, private fields can be used in abstract classes and are accessible only within the class itself.
Example
AbstractShape class
Circle Class
Square class
Main Class
Constructors in Abstract Classes
While abstract classes cannot be instantiated directly, they can have constructors. These constructors are primarily used to initialize fields or perform setup tasks that are common across all subclasses. When a subclass of an abstract class is instantiated, the constructor of the abstract class is called as part of the instantiation chain.
This feature is essential because it allows abstract classes to set up necessary state or dependencies that subclasses rely on. Additionally, since subclasses must call the constructor of the abstract superclass, this approach provides consistency in initialization.
Abstract classes can have protected constructors, a technique used to control instantiation and ensure subclasses inherit but cannot create instances directly outside their package.
Here, the protected constructor in BaseComponent prevents instantiation from outside the class hierarchy, emphasizing that this class is intended solely for inheritance.
Other Example
Static Methods in Abstract Classes
Static methods belong to the class itself rather than to any specific instance. In abstract classes, static methods can provide utility functions or helper methods relevant to the class as a whole. Because static methods do not depend on an instance, they’re often used to perform operations that do not require access to non-static fields of the class.
Since abstract classes can contain both static methods and abstract methods, this structure is more versatile than interfaces (which traditionally only contained abstract methods prior to Java 8).
Nested Abstract Class
Abstract class in Java can contain inner abstract classes, inner concrete classes, and static methods within it.
An inner class is defined within the scope of an outer class. Java supports different types of inner classes, which can also be abstract or concrete:
Non-static Inner Class (Instance Inner Class): Tied to an instance of the outer class. It has access to the outer class’s instance members.
Static Inner Class: Similar to a regular class but nested within an outer class. It doesn’t require an instance of the outer class to be instantiated and can only access static members of the outer class.
Types of Inner Classes
Abstract Inner Class: Defines an abstract class within an outer class, requiring subclasses (either nested or external) to implement its methods.
Concrete Inner Class: Provides a fully implemented inner class that can operate within the context of the outer class.
Abstract Classes and Dependency Injection
Abstract classes can serve as base types in dependency injection (DI) configurations in frameworks such as Spring. They can provide foundational, unchanging methods while enforcing specific functionalities in subclasses.
Abstract Classes in Design Patterns
Abstract classes are often foundational in design patterns, particularly in cases like the Template Method, Factory Method, and Adapter Pattern.
Template Method Pattern
Defines the skeleton of an algorithm in an abstract class, allowing subclasses to override certain steps without altering the algorithm's structure.
Factory Method Pattern
In the Factory Method Pattern, an abstract class defines a method for creating an object, but allows subclasses to alter the type of object that will be created. This pattern is particularly useful for scenarios where the creation process of an object requires customization by subclasses.
Let’s consider a scenario where we have different types of Document objects: WordDocument and PDFDocument. Each document type has its own way of preparing content.
Adapter Pattern
In the Adapter Pattern, an abstract class or interface defines a target interface that different adapters can implement to wrap incompatible classes. This pattern is often used when integrating with third-party libraries or legacy systems that have incompatible interfaces.
Consider a scenario where we have an existing Rectangle class in a legacy system, but we want to use it in a new system that expects Shape objects.
Abstract Class with multiple inheritance
Abstract classes in Java do not support multiple inheritance. In Java, a class (whether abstract or concrete) can extend only one superclass, which is a constraint to avoid complexities that can arise from multiple inheritance, such as the Diamond Problem.
The Diamond Problem
The Diamond Problem is a classic issue in languages that support multiple inheritance (such as C++). This problem occurs when two parent classes inherit from a common superclass, and a subclass then inherits from both of these parents. The ambiguity arises because the subclass has two paths to the superclass, which could lead to conflicts in inherited behavior or state.
For example:
Imagine
ClassAandClassBeach inherit from a common superclass,ClassC.If
ClassDthen extends bothClassAandClassB, there’s a risk of ambiguity as to which version ofClassC's methods or fieldsClassDshould inherit.
To avoid this complexity, Java allows each class (abstract or concrete) to extend only a single class
Last updated