Abstraction in Java involves concealing the inner workings of a component and revealing only the essential functionalities to the user. It focuses on describing the actions performed by an object rather than the method by which they are executed.
Features of Abstraction
- Abstraction highlights only the essential features while hiding the complex details.
- Abstract classes can contain methods without implementation and should be implemented by subclasses.
- Due to the principles of abstraction, code that depends on it remains unaffected.
- Changes in implementation do not affect the external usage of the class.
- It restricts direct access to implementation details, ensuring enhanced security and modularity.
- It promotes loose coupling by minimising dependencies between components, thereby making the system more scalable.
- It avoids code duplication.
Real World Example of Abstraction
ATM Device: Utilizing an ATM involves engaging with a straightforward interface where you input your PIN, choose an action, and retrieve funds. However, the intricate backend operations such as authentication, validating transactions, and communicating with the bank's servers remain concealed from the user, keeping the internal mechanisms out of view.
Operating a Vehicle: As we operate a vehicle, we engage with the steering wheel, accelerator pedal, and brake pedal without delving into the specifics of the internal functioning of the engine, transmission, and braking mechanism. The vehicle simplifies the intricacies, enabling us to concentrate on the act of driving.
Achieving Abstraction
Abstraction in Java can be implemented through two methods:
- By utilizing an Abstract Class to achieve partial abstraction.
- By employing an Interface to achieve full abstraction.
1) Using Abstract Class
An abstract class is a class that cannot be instantiated directly, functioning as a template for other classes. The abstract keyword is used to declare an abstract class.
Important Points to Remember
- An abstract class is a class declared with the abstract keyword.
- An abstract method is a method declared without any implementation .
- An abstract class can contain both abstract and concrete methods (where implementation is present).
- A child class whose parent is an abstract class must implement the abstract method. If the child class cannot provide the implementation, then it must be declared as abstract .
- Any class that contains one or more abstract methods must be declared as abstract .
- Instantiation of an abstract class is not allowed in Java. In other words, one cannot create an object of an abstract class using the new keyword.
- If no constructor is provided, an abstract class has a default constructor . An abstract class can also include user-defined constructors .
- Creating more than one constructor is permitted in an abstract class.
To read more Abstract Class in Java
Syntax
abstract class <class-name> {
...
}
Abstract Methods
An abstract method is a method lacking an implementation and must be defined by subclasses.
To read more Abstract Method in Java
Syntax
abstract return_type <method-name> {
...
}
Example of Abstract Class
Example
abstract class Animal {
abstract void makeSound(); // Abstract method (no implementation)
void eat() { // Concrete method
System.out.println("I can eat.");
}
}
class Dog extends Animal {
void makeSound() { //overrides the makeSound() method of the Animal class
System.out.println("Bark bark");
}
}
public class Main {
public static void main(String[] args) {
Dog d1 = new Dog();
d1.makeSound(); //invokes the Dog class makeSound() method
d1.eat(); //invokes the Animal class eat() method
}
}
Output:
Bark bark
I can eat.
To read more Java Abstract Class and Methods
When to Use Abstract Class?
Utilizing abstract classes and abstract methods is essential for establishing a shared template for various interconnected classes, enabling the incorporation of distinct functionalities.
We should use abstract classes in the following cases.
- If multiple related classes share common functionality, an abstract class can provide default implementations.
- When we want to provide some implemented methods while leaving other methods for implementation in subclasses.
- If the program design follows an inheritance-based design and has IS-A For example, Parent is a superclass for Father and Son.
- It helps to avoid code duplication by centralizing shared logic.
We should use abstract methods in the following cases.
- If all subclasses require a specific functionality, define it as an abstract method.
- Abstract methods ensure that their implementation will be provided in subclasses.
- Enables various subclasses to implement the method uniquely while preserving consistency.
2) Using Interface
Another method to achieve abstraction in Java is through the utilization of interfaces. Interfaces are valuable for attaining complete abstraction. They encompass variables and methods in Java, as well as in various other programming languages, devoid of method implementations.
Subsequently, subclasses are required to define each method from the interface. Interfaces allow for multiple inheritance as well. It is important to remember that interface methods are inherently public and abstract.
To read more Interface in Java
Within the provided code excerpt, the Bike class is utilizing the Drivable interface and has additionally implemented the drive function.
class Bike implements Drivable {
@Override
public void drive() {
System.out.println("Bike is driving");
}
}
Example of Abstraction Using Interface
Example
interface Person {
void display();
}
class Student implements Person {
public void display() {
System.out.println("This is the display method of the student class");
}
}
class Lecturer implements Person {
public void display() {
System.out.println("This is the display method of the lecturer class");
}
}
public class Main {
public static void main(String[] args) {
Person person1 = new Student();
person1.display();
Person person2 = new Lecturer();
person2.display();
}
}
Output:
This is the display method of the student class
This is the display method of the lecturer class
Advantages of Abstraction
- By hiding the implementation details, abstraction makes complex systems easier to comprehend.
- Abstraction maintains various components of the system separated.
- Maintenance of code is done more efficiently using abstraction.
- Abstraction enhances security by only displaying the details that are necessary to the user.
- If overused, abstraction can add unnecessary complexity.
- Flexibility in implementation may be reduced using abstraction.
- Abstraction can make understanding the system and debugging harder for unfamiliar users.
- Performance can be affected by the layers of abstraction.
Disadvantages of Abstraction
Common Mistakes to Avoid
The following is a list of common errors that can occur while working with abstraction, which should be avoided:
- Ensure that in the concrete subclass, abstract methods are implemented.
- Avoid making everything abstract when it is not required. Use abstraction only when it enhances the design.
- When abstract methods are overridden, ensure the method signature matches exactly; otherwise, it can cause errors.
- Use abstract classes when a common base class with shared functionality is needed.
- Use interfaces when complete abstraction or multiple inheritance is required.
- Keep interfaces small and focused; never include unrelated methods in a single interface.
Best Practices
Conclusion
Abstraction in Java plays a crucial role in simplifying object-oriented programming by highlighting only the key features of objects or systems to developers. By utilizing abstract classes and interfaces, developers can design systems that are easy to reuse, portable, and less complex.
Java Abstraction MCQs
- Which keyword is used to create an abstract class?
- abstract
- assert
- native
- private
Explanation: The abstract keyword in Java is used to declare an abstract class.
- How can you achieve abstraction in Java?
- Only through abstract methods
- Only through abstract classes
- Only through Interfaces
- Both 2 and 3
Explanation: Abstraction in Java can be achieved using both abstract classes and interfaces. Using the interface, we can achieve 100% abstraction.
- An abstract class can contain__________?
- Default Method Only
- Abstract Method Only
- Concrete Method Only
- Both 2 and 3
Explanation: An abstract class can contain both abstract (without any implementation) and concrete methods (where implementation is present).
- What is the main objective of abstraction?
- To showcase the implementation
- To showcase essential features
- To showcase complex functionalities
- All the above
Explanation: Abstraction emphasizes showcasing only the essential features of an object while keeping its intricate details concealed.
- Why use abstraction?
- It promotes reusability
- It promotes modularity
- It promotes extensibility
- All the above
By advocating for code reusability, modularity, and extensibility, it facilitates the maintenance and scalability of software systems.