Abstract Classes and Methods:
Data abstraction is the process of hiding certain details and showing only essential information to the user.
Abstraction can be achieved with either abstract classes or interfaces .
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).
Points to Remember:
- An abstract class must be declared with an abstract keyword.
- It can have abstract and non-abstract methods.[TBD]
- It cannot be instantiated.
- It can have constructors and static methods also.
- It can have final methods which will force the subclass not to change the body of the method.
Abstract Class:
A class which contains the abstract keyword in its declaration is known as abstract class.
- 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.
- 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 having both abstract methods and non-abstract methods.
- Declaring a class as abstract with no abstract methods means that we don’t allow it to be instantiated on its own.[TBD]
- An abstract class can extend only one class or one abstract class at a time.[TBD]
Java Abstract Method:
A method that doesn’t have its body is known as an abstract method. We use the same abstract keyword to create abstract methods.
abstract void display();
Advantage:

Abstract class having constructor, data member and methods:
An abstract class can have a data member, abstract method, method body (non-abstract method), constructor, and even main() method.
//Example of an abstract class that has abstract and non-abstract methods
abstract class Bike{
Bike(){System.out.println("bike is created");}
abstract void run();
void changeGear(){System.out.println("gear changed");}
}
//Creating a Child class which inherits Abstract class
class Honda extends Bike{
void run(){System.out.println("running safely..");}
}
//Creating a Test class which calls abstract and non-abstract methods
class TestAbstraction2{
public static void main(String args[]){
Bike obj = new Honda(); [TBD]
obj.run();
obj.changeGear();
}
}
Reference:
https://www.tutorialspoint.com/java/java_abstraction.htm
https://www.w3schools.com/java/java_abstract.asp
https://www.programiz.com/java-programming/abstract-classes-methods
Leave a comment