Java Tutorial 40 of 143
Basics
- Introduction
- Download and Install Java
- Download and Install IntelliJ IDEA, Eclipse
- Creating First Java Application in IntelliJ IDEA
- JDK vs JRE vs JVM
- Print output
- Taking Input
- Identifiers
- Keywords
- Variables
- Data Types
- Literals
- Wrapper Classes
- Operators
- Decision Making
- Loops and Jump Statements
- Project: Number Guessing Game
Methods
- Introduction
- Static Methods vs Instance Methods
- Access Modifiers
- Command Line Arguments
- Variable Arguments (Varargs)
Arrays
- Introduction
- One Dimensional Arrays
- Multidimensional Arrays
- Array Class
- Arrays Class
Strings
- Introduction
- String
- StringBuffer
- StringBuilder
- String Class Methods
- StringJoiner
- StringTokenizer
OOP & Interface
- Introduction
- Java Constructors
- Java Encapsulation
- Inheritance
- Java Polymorphism
- Java Abstraction
- Interfaces
- this Keyword
- super Keyword
- static Keyword
- final Keyword
- Access Modifiers
- Nested Classes
- Anonymous Inner Class
Collections
- Collection class
- Collection Interface
- List Interface
- ArrayList
- LinkedList
- Set Interface
- HashSet
- LinkedHashSet
- TreeSet
- Queue Interface
- PriorityQueue
- Deque
- ArrayDeque
- Map Interface in Java
- HashMap
- LinkedHashMap
- TreeMap
- Hashtable
- Iterator
- Comparable and Comparator
Exception Handling
- Introduction
- Java Exception Handling
- Java Try-Catch
- Java Finally Block
- Java throw and throws
- Java Custom Exceptions
- Java Checked vs Unchecked Exceptions
Multithreading & Concurrency
- Introduction
- Thread Class
- Runnable Interface
- Thread Life Cycle
- Thread Priority
- Synchronization
- Inter-Thread Communication
- Executor Framework
- Callable and Future
- Concurrent Collections
Java 8 Features
- Lambda Expressions
- Functional Interfaces
- Method References
- Stream API
- Optional Class
- Default and Static Methods in Interface
- Date and Time API
Advanced Java Concepts
- File Handling
- Serialization and Deserialization
- Reflection API
- Annotations
- Garbage Collection
- Memory Management
- JVM Architecture
- Class Loading
- Networking
- Regular Expressions
JDBC
- Introduction
- JDBC Driver
- JDBC Connection
- Types of Statements in JDBC
- Transactions
- ResultSet
- Metadata
- Connection Pooling
Web & Enterprise
- Servlets
- JSP
- Spring Framework
- Spring Boot
- Hibernate
- REST API Development
Practice Projects
- Project: Number Guessing Game
- Project: Banking System
- Project: Student Management System
- Project: Library Management System
- Project: Quiz Application
Quiz and Coding Practice
- Java Topic-wise Quiz
- Coding Practice Problems
- Java Basics Coding Practice Problems
- Java Exercises
Interview Questions
- Core Java Interview Questions and Answers
- Advanced Java Interview Questions and Answers
- Java Interview Questions
DSA & Competitive Programming
- Arrays and Strings
- Linked List
- Stack
- Queue
- Tree
- Graph
- Heap
- Hashing
- Sorting
- Searching
- Dynamic Programming
- Roadmap for DSA in Java
Java Abstraction
Learn Java abstraction using abstract classes and interfaces to hide implementation details, define common behavior, and build flexible object-oriented applications.
On this page
- What Is Abstraction in Java?
- Example
- Abstract Classes in Java
- Abstract Methods
- Rules of Abstract Methods
- Can We Create an Object of an Abstract Class?
- Abstract Class with a Constructor
- Abstract Class with Concrete Methods
- Example: Abstraction Using a Payment System
- Abstraction vs Encapsulation
- Abstraction vs Interface
- Advantages of Abstraction
- 1. Hides Implementation Complexity
- 2. Improves Maintainability
- 3. Supports Loose Coupling
- 4. Supports Polymorphism
- 5. Improves Code Organization
- Key Points to Remember
- Conclusion
Java Abstraction
Abstraction is one of the fundamental concepts of object-oriented programming (OOP) in Java. It allows you to hide unnecessary implementation details and expose only the essential features of an object.
For example, when you use a car, you interact with controls such as the steering wheel, accelerator, and brakes. You do not need to know how the engine internally works. This is an example of abstraction.
In Java, abstraction can be achieved primarily using:
- Abstract classes
- Abstract methods
- Interfaces
What Is Abstraction in Java?
Abstraction means hiding the internal implementation of an object and showing only the functionality that is relevant to the user.
Consider a payment system. A user may call:
payment.pay(1000);
The user does not need to know whether the payment is processed through a bank, credit card, or another internal service.
The implementation can remain hidden while the required functionality is exposed.
Example
abstract class Animal {
abstract void makeSound();
void sleep() {
System.out.println("Animal is sleeping");
}
}
Here, makeSound() defines what an animal should do, but the class does not specify how every animal makes its sound.
A subclass provides the implementation:
class Dog extends Animal {
@Override
void makeSound() {
System.out.println("Dog barks");
}
}
Using the class:
public class Main {
public static void main(String[] args) {
Dog dog = new Dog();
dog.makeSound();
dog.sleep();
}
}
Output:
Dog barks
Animal is sleeping
The Animal class defines the required behavior, while Dog provides the implementation.
Abstract Classes in Java
An abstract class is a class declared using the abstract keyword.
It can contain:
- Abstract methods
- Concrete methods
- Constructors
- Variables
- Static methods
- Instance methods
Example:
abstract class Vehicle {
abstract void start();
void stop() {
System.out.println("Vehicle stopped");
}
}
The class contains an abstract method start() and a concrete method stop().
A subclass can implement the abstract method:
class Car extends Vehicle {
@Override
void start() {
System.out.println("Car started");
}
}
Abstract Methods
An abstract method is a method declared without an implementation.
It uses the abstract keyword.
Syntax:
abstract returnType methodName();
Example:
abstract class Shape {
abstract void draw();
}
The method draw() has no method body.
A concrete subclass must provide its implementation:
class Circle extends Shape {
@Override
void draw() {
System.out.println("Drawing a circle");
}
}
Rules of Abstract Methods
There are several important rules to remember:
- An abstract method does not have a method body.
- An abstract method must be declared inside an abstract class or interface.
- A concrete subclass must implement all inherited abstract methods.
- An abstract method cannot be
private. - An abstract method cannot be
final. - An abstract method cannot be
static.
For example:
abstract class Animal {
abstract void sound();
}
The subclass must implement sound() unless the subclass is also abstract.
Can We Create an Object of an Abstract Class?
No. An abstract class cannot be instantiated directly.
The following code is invalid:
abstract class Animal {
abstract void sound();
}
public class Main {
public static void main(String[] args) {
Animal animal = new Animal(); // Error
}
}
However, an abstract class can be used as a reference type:
Animal animal = new Dog();
Here, the object is actually a Dog, while the reference type is Animal.
This is commonly used with polymorphism.
Abstract Class with a Constructor
An abstract class can have a constructor.
Although you cannot directly create an object of the abstract class, its constructor is executed when an object of a subclass is created.
Example:
abstract class Animal {
Animal() {
System.out.println("Animal constructor");
}
abstract void sound();
}
class Dog extends Animal {
Dog() {
System.out.println("Dog constructor");
}
@Override
void sound() {
System.out.println("Dog barks");
}
}
Using the class:
Dog dog = new Dog();
Output:
Animal constructor
Dog constructor
The parent constructor executes before the child constructor.
Abstract Class with Concrete Methods
An abstract class can contain both abstract and concrete methods.
Example:
abstract class Vehicle {
abstract void start();
void stop() {
System.out.println("Vehicle stopped");
}
}
Here:
start()is an abstract method.stop()is a concrete method.
This allows an abstract class to provide some common implementation while leaving specific behavior to subclasses.
Example: Abstraction Using a Payment System
Consider a payment application.
Different payment methods can implement payment differently.
abstract class Payment {
abstract void pay(double amount);
void paymentStarted() {
System.out.println("Payment process started");
}
}
A credit card implementation:
class CreditCardPayment extends Payment {
@Override
void pay(double amount) {
System.out.println("Paid ₹" + amount + " using credit card");
}
}
A UPI implementation:
class UpiPayment extends Payment {
@Override
void pay(double amount) {
System.out.println("Paid ₹" + amount + " using UPI");
}
}
The application can use the abstraction:
public class Main {
public static void main(String[] args) {
Payment payment = new UpiPayment();
payment.paymentStarted();
payment.pay(1000);
}
}
Output:
Payment process started
Paid ₹1000.0 using UPI
The Payment abstraction defines what a payment should do, while each implementation determines how it is performed.
Abstraction vs Encapsulation
Abstraction and encapsulation are related but different concepts.
| Abstraction | Encapsulation |
|---|---|
| Hides implementation details | Hides and protects internal data |
| Focuses on what an object does | Focuses on how data and behavior are bundled |
| Commonly implemented using abstract classes and interfaces | Commonly implemented using classes and access modifiers |
| Helps reduce implementation complexity | Helps control access to data |
For example, an ATM provides a simple interface for withdrawing money. You do not need to know the internal banking operations. This represents abstraction.
A bank account may keep its balance private and provide controlled methods such as deposit() and withdraw(). This represents encapsulation.
Abstraction vs Interface
Both abstract classes and interfaces can be used to achieve abstraction, but they serve somewhat different purposes.
| Abstract Class | Interface |
|---|---|
Declared using abstract class |
Declared using interface |
| Can contain instance variables | Fields are implicitly constants (public static final) |
| Can have constructors | Cannot have constructors |
| Can contain concrete methods | Can contain abstract and, in modern Java, default/static/private methods |
| A class can extend only one class | A class can implement multiple interfaces |
Example of an interface:
interface Vehicle {
void start();
}
Implementation:
class Car implements Vehicle {
@Override
public void start() {
System.out.println("Car started");
}
}
Interfaces are particularly useful when unrelated classes need to follow the same contract.
Advantages of Abstraction
Abstraction provides several benefits:
1. Hides Implementation Complexity
Users interact with a simple interface without needing to understand internal implementation.
2. Improves Maintainability
Implementation details can change without requiring changes to code that uses the abstraction.
3. Supports Loose Coupling
Code can depend on abstractions rather than specific implementations.
For example:
Payment payment = new UpiPayment();
The application depends on Payment rather than directly depending on all implementation details.
4. Supports Polymorphism
Different classes can provide different implementations of the same abstract behavior.
Payment payment;
payment = new UpiPayment();
payment.pay(500);
payment = new CreditCardPayment();
payment.pay(500);
5. Improves Code Organization
Common functionality can be placed in an abstract parent class while specialized behavior is implemented by subclasses.
Key Points to Remember
- Abstraction hides implementation details and exposes essential functionality.
- Java supports abstraction through abstract classes and interfaces.
- An abstract class cannot be instantiated directly.
- An abstract class can contain both abstract and concrete methods.
- An abstract method does not have a method body.
- Concrete subclasses must implement inherited abstract methods unless they are also abstract.
- Abstract classes can have constructors.
- Abstraction helps reduce complexity and supports polymorphism.
- Interfaces are another important mechanism for abstraction in Java.
Conclusion
Abstraction in Java allows developers to focus on what an object does rather than how it performs its work internally. Abstract classes provide a way to define common behavior while leaving specific implementation to subclasses.
By combining abstraction with encapsulation, inheritance, and polymorphism, Java developers can build code that is easier to maintain, extend, and understand.
Related
-
Inheritance
Learn Java inheritance, including single, multilevel, and hierarchical inheritance, method overriding, super, and how inheritance supports code reuse and polymorphism.
-
Java Polymorphism
Learn Java polymorphism, including compile-time and runtime polymorphism, method overloading, method overriding, dynamic method dispatch, and practical examples.
-
Java Constructors
Learn Java constructors, including default and parameterized constructors, constructor overloading, chaining, and how constructors initialize objects.
-
Java Encapsulation
Learn Java encapsulation, how to protect object data using access modifiers, getters and setters, and why encapsulation improves code security and maintainability.