Abstraction and Abstract class in Java
Let's first understand the concept of abstraction in java. Abstraction is a process of hiding the implementation details and showing only functionality to the user. hiding the internal details it only shows what's necessary to the user
A class which is declared with the abstract keyword is known as an abstract class in Java. It can have abstract and non-abstract methods (method with the body).
Abstract class in Java
A class which is declared as abstract is known as an abstract class. It can have abstract and non-abstract methods. It needs to be extended and its method implemented.
Points to Remember
An abstract class must be declared with an abstract keyword.
It can have both abstract and non abstract methods.
It cannot be instantiated.
Example of abstract method
abstract void printStatus();//no method body and abstract
Example of Abstract class that has an abstract method
abstract class Car{
abstract void run();
}
class Honda extends Car{
void run(){
System.out.println("running safely");
}
public static void main(String args[]){
Car obj = new Honda();
obj.run();
}
}
Abstract class having constructor, data member and methods
//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 city extends Bike{
void run(){
System.out.println("running safely..");
}
}
//Creating a Test class which calls abstract and non-abstract methods
class TestAbstraction{
public static void main(String args[]){
Bike obj = new city();
obj.run();
obj.changeGear();
}
}