read gfg,w3schools,tutorialpoint,programmiz
Abstraction is a process of hiding the implementation details from the user, only the functionality will be provided to the use ,showing only essential features. In other words, the user will have the information on what the object does instead of how it does it. In Java programming, abstraction is achieved using Abstract classes and interfaces.It focuses on what an object does rather than how it does it.
- It hides the complex details and shows only essential features. Abstract classes may have methods without implementation and must be implemented by subclasses. By abstracting functionality, changes in the implementation do not affect the code that depends on the abstraction.
Java provides two ways to implement abstraction, which are listed below:
Abstract Classes (Partial Abstraction)
Interface (provides abstraction for behavior, may contain default or static methods)
Example:
abstract class Animal {
abstract void sound(); // abstract method
void sleep() { // concrete method
System.out.println("Sleeping...");
}
}
class Dog extends Animal {
void sound() {
System.out.println("Barking");
}
}
Explanation:
Animal is an abstract class → cannot be instantiated.
sound() is abstract → must be implemented by Dog.
sleep() is shared by all animals.
Key Points:
You cannot create objects of an abstract class.
It is mainly used for inheritance and design structure.
Helps in writing clean, maintainable, and scalable code.
Why we use abstract in Java:
To define a common blueprint
An abstract class provides a base structure for other classes.
It ensures that all subclasses follow the same design.
To enforce method implementation
Abstract methods (methods without a body) must be implemented by subclasses.
This guarantees that certain behaviors are defined in child classes.
To achieve partial abstraction
Advantages of Abstraction
Abstraction makes complex systems easier to understand by hiding the implementation details.
Abstraction keeps different part of the system separated.
Abstraction maintains code more efficiently.
Abstraction increases the security by only showing the necessary details to the user.
Disadvantages of Abstraction
It can add unnecessary complexity if overused.
May reduce flexibility in implementation.
Makes debugging and understanding the system harder for unfamiliar users.
Overuse of abstraction may make code harder to follow, though performance impact is usually negligible.
Common Mistakes to Avoid
Not Implementing Abstract Methods: Always make sure that the abstract methods are implemented in the concrete subclass.
Overusing Abstraction: Avoid making everything abstract when it’s not required. Use abstraction only when it enhances the design.
Inconsistent Method Signatures in Subclasses: When you override abstract methods, please make sure the method signature matches exactly, any mistake can cause errors.
An abstract class can have both:
Abstract methods (no body)
Concrete methods (with body)
To avoid code duplication
Common code can be written once in the abstract class and reused by subclasses.
Java Abstract Classes
A Java class which contains the abstract keyword in its declaration is known as abstract class.
Java abstract classes may or may not contain abstract methods, i.e., methods without body ( public void get(); )
But, if a class has at least one abstract method, then the class must be declared abstract.
If a class is declared abstract, it cannot be instantiated(we cannot create objects of abstract classes).
To use an abstract class, you have to inherit it from another class, provide implementations to the abstract methods in it.
If you inherit an abstract class, you have to provide implementations to all the abstract methods in it.
An abstract class can have both the regular methods and abstract methods.
abstract class Language {
// abstract method
abstract void method1();
// regular method
void method2() {
System.out.println("This is regular method");
}
}
Example: Java Abstract Class
To create an abstract class in Java, just use the abstract keyword before the class keyword, in the class declaration.
/* File name : Employee.java */
public abstract class Employee {
private String name;
private String address;
private int number;
public Employee(String name, String address, int number) {
System.out.println("Constructing an Employee");
this.name = name;
this.address = address;
this.number = number;
}
public double computePay() {
System.out.println("Inside Employee computePay");
return 0.0;
}
public void mailCheck() {
System.out.println("Mailing a check to " + this.name + " " + this.address);
}
public String toString() {
return name + " " + address + " " + number;
}
public String getName() {
return name;
}
public String getAddress() {
return address;
}
public void setAddress(String newAddress) {
address = newAddress;
}
public int getNumber() {
return number;
}
}
Explanation:except abstract methods the Employee class is same as normal class in Java. The class is now abstract, but it still has three fields, seven methods, and one constructor.
Inheriting the Java Abstract Class
We can inherit the properties of Employee class just like concrete class .
/* File name : Salary.java */
public class Salary extends Employee {
private double salary; // Annual salary
public Salary(String name, String address, int number, double salary) {
super(name, address, number);
setSalary(salary);
}
public void mailCheck() {
System.out.println("Within mailCheck of Salary class ");
System.out.println("Mailing check to " + getName() + " with salary " + salary);
}
public double getSalary() {
return salary;
}
public void setSalary(double newSalary) {
if(newSalary >= 0.0) {
salary = newSalary;
}
}
public double computePay() {
System.out.println("Computing salary pay for " + getName());
return salary/52;
}
}
Here, you cannot instantiate the Employee class, but you can instantiate the Salary Class, and using this instance you can access all the three fields and seven methods of Employee class.
/* File name : AbstractDemo.java */
public class AbstractDemo {
public static void main(String [] args) {
Salary s = new Salary("Mohd Mohtashim", "Ambehta, UP", 3, 3600.00);
Employee e = new Salary("John Adams", "Boston, MA", 2, 2400.00);
System.out.println("Call mailCheck using Salary reference --");
s.mailCheck();
System.out.println("\n Call mailCheck using Employee reference--");
e.mailCheck();
}
}
abstract class Employee {
private String name;
private String address;
private int number;
public Employee(String name, String address, int number) {
System.out.println("Constructing an Employee");
this.name = name;
this.address = address;
this.number = number;
}
public double computePay() {
System.out.println("Inside Employee computePay");
return 0.0;
}
public void mailCheck() {
System.out.println("Mailing a check to " + this.name + " " + this.address);
}
public String toString() {
return name + " " + address + " " + number;
}
public String getName() {
return name;
}
public String getAddress() {
return address;
}
public void setAddress(String newAddress) {
address = newAddress;
}
public int getNumber() {
return number;
}
}
class Salary extends Employee {
private double salary; // Annual salary
public Salary(String name, String address, int number, double salary) {
super(name, address, number);
setSalary(salary);
}
public void mailCheck() {
System.out.println("Within mailCheck of Salary class ");
System.out.println("Mailing check to " + getName() + " with salary " + salary);
}
public double getSalary() {
return salary;
}
public void setSalary(double newSalary) {
if(newSalary >= 0.0) {
salary = newSalary;
}
}
public double computePay() {
System.out.println("Computing salary pay for " + getName());
return salary/52;
}
}
Output
Constructing an Employee
Constructing an Employee
Call mailCheck using Salary reference --
Within mailCheck of Salary class
Mailing check to Mohd Mohtashim with salary 3600.0
Call mailCheck using Employee reference--
Within mailCheck of Salary class
Mailing check to John Adams with salary 2400.0
Why And When To Use Abstract Classes and Methods?
To achieve security - hide certain details and only show the important details of an object.
Abstraction can also be achieved with Interfaces
Abstract Keyword
The abstract keyword is a non-access modifier, used for classes and methods:
Abstract class: is a restricted class that cannot be used to create objects (to access it, it must be inherited from another class).
Abstract method: can only be used in an abstract class, and it does not have a body. The body is provided by the subclass (inherited from).
An abstract method belongs to an abstract class, and it does not have a body. The body is provided by the subclass
An abstract class can have both abstract and regular methods.
Java Abstract Methods
a class to contain a particular method but you want the actual implementation of that method to be determined by child classes, you can declare the method in the parent class as an abstract.
- abstract keyword is used to declare the method as abstract.
- You have to place the abstract keyword before the method name in the method declaration.
- An abstract method contains a method signature, but no method body.
- Instead of curly braces, an abstract method will have a semi colon (;) at the end.
A method that doesn't have its body is known as an abstract method.
abstract void display();
Here, display() is an abstract method. The body of display() is replaced by ;.
If a class contains an abstract method, then the class should be declared abstract. Otherwise, it will generate an error. For example,
// error
// class should be abstract
class Language {
// abstract method
abstract void method1();
}
Example 1: Implementing Abstract Method in Java
public abstract class Employee {
private String name;
private String address;
private int number;
public abstract double computePay();
// Remainder of class definition
}
Declaring a method as abstract has two consequences −
- The class containing it must be declared as abstract.
- Any class inheriting the current class must either override the abstract method or declare itself as abstract.
Note − Eventually, a descendant class has to implement the abstract method; otherwise, you would have a hierarchy of abstract classes that cannot be instantiated.
Suppose Salary class inherits the Employee class, then it should implement the computePay() method as shown below −
/* File name : Salary.java */
public class Salary extends Employee {
private double salary; // Annual salary
public double computePay() {
System.out.println("Computing salary pay for " + getName());
return salary/52;
}
// Remainder of class definition
}
Example 2: Implementing Abstract Method in Java
/* File name : AbstractDemo.java */
public class AbstractDemo {
public static void main(String [] args) {
Salary s = new Salary("Mohd Mohtashim", "Ambehta, UP", 3, 3600.00);
System.out.println("salary: " + s.computePay());
}
}
abstract class Employee {
private String name;
private String address;
private int number;
public Employee(String name, String address, int number) {
System.out.println("Constructing an Employee");
this.name = name;
this.address = address;
this.number = number;
}
public abstract double computePay();
// Remainder of class definition
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public int getNumber() {
return number;
}
public void setNumber(int number) {
this.number = number;
}
}
class Salary extends Employee {
private double salary; // Annual salary
public Salary(String name, String address, int number, double salary) {
super(name, address, number);
this.salary = salary;
}
public double computePay() {
System.out.println("Computing salary pay for " + getName());
return salary/52;
}
// Remainder of class definition
}
Output
Constructing an Employee
Computing salary pay for Mohd Mohtashim
salary: 69.23076923076923
**
Example: Java Abstract Class and Method**
Though abstract classes cannot be instantiated, we can create subclasses from it. We can then access members of the abstract class using the object of the subclass. For example,
abstract class Language {
// method of abstract class
public void display() {
System.out.println("This is Java Programming");
}
}
class Main extends Language {
public static void main(String[] args) {
// create an object of Main
Main obj = new Main();
// access method of abstract class
// using object of Main class
obj.display();
}
}
Output
This is Java programming
we have created an abstract class named Language. The class contains a regular method display().
We have created the Main class that inherits the abstract class. Notice the statement,
obj.display();
Here, obj is the object of the child class Main. We are calling the method of the abstract class using the object obj.
Implementing Abstract Methods
If the abstract class includes any abstract method, then all the child classes inherited from the abstract superclass must provide the implementation of the abstract method. For example,
abstract class Animal {
abstract void makeSound();
public void eat() {
System.out.println("I can eat.");
}
}
class Dog extends Animal {
// provide implementation of abstract method
public void makeSound() {
System.out.println("Bark bark");
}
}
class Main {
public static void main(String[] args) {
// create an object of Dog class
Dog d1 = new Dog();
d1.makeSound();
d1.eat();
}
}
Output
Bark bark
I can eat.
we have created an abstract class Animal. The class contains an abstract method makeSound() and a non-abstract method eat().
We have inherited a subclass Dog from the superclass Animal. Here, the subclass Dog provides the implementation for the abstract method makeSound().
We then used the object d1 of the Dog class to call methods makeSound() and eat().
Note: If the Dog class doesn't provide the implementation of the abstract method makeSound(), Dog should also be declared as abstract. This is because the subclass Dog inherits makeSound() from Animal.
Accesses Constructor of Abstract Classes
An abstract class can have constructors like the regular class. And, we can access the constructor of an abstract class from the subclass using the super keyword. For example,
abstract class Animal {
Animal() {
….
}
}
class Dog extends Animal {
Dog() {
super();
...
}
}
Here, we have used the super() inside the constructor of Dog to access the constructor of the Animal.
Note that the super should always be the first statement of the subclass constructor.
This allows us to manage complexity by omitting or hiding details with a simpler, higher-level idea.
A practical example of abstraction can be motorbike brakes. We know what brake does. When we apply the brake, the motorbike will stop. However, the working of the brake is kept hidden from us.
The major advantage of hiding the working of the brake is that now the manufacturer can implement brake differently for different motorbikes, however, what brake does will be the same.
Example 3: Java Abstraction
abstract class MotorBike {
abstract void brake();
}
class SportsBike extends MotorBike {
// implementation of abstract method
public void brake() {
System.out.println("SportsBike Brake");
}
}
class MountainBike extends MotorBike {
// implementation of abstract method
public void brake() {
System.out.println("MountainBike Brake");
}
}
class Main {
public static void main(String[] args) {
MountainBike m1 = new MountainBike();
m1.brake();
SportsBike s1 = new SportsBike();
s1.brake();
}
}
Output:
MountainBike Brake
SportsBike Brake
In the above example, we have created an abstract super class MotorBike. The superclass MotorBike has an abstract method brake().
The brake() method cannot be implemented inside MotorBike. It is because every bike has different implementation of brakes. So, all the subclasses of MotorBike would have different implementation of brake().
So, the implementation of brake() in MotorBike is kept hidden.
Here, MountainBike makes its own implementation of brake() and SportsBike makes its own implementation of brake().
Note: We can also use interfaces to achieve abstraction in Java. To learn more, visit Java Interface.
Key Points to Remember
We use the abstract keyword to create abstract classes and methods.
An abstract method doesn't have any implementation (method body).
A class containing abstract methods should also be abstract.
We cannot create objects of an abstract class.
To implement features of an abstract class, we inherit subclasses from it and create objects of the subclass.
A subclass must override all abstract methods of an abstract class. However, if the subclass is declared abstract, it's not mandatory to override abstract methods.
We can access the static attributes and methods of an abstract class using the reference of the abstract class. For example,
Animal.staticMethod();
Top comments (0)