JAVA ABSTRACT
class
Abstract class
An abstract class is a class that cannot be instantiated (we cannot create objects of an abstract
class). In Java, we use the abstract keyword to declare an abstract class.
// An example abstract class in Java
abstract class Shape {
int color;
// An abstract function (like a pure virtual function in C++)
abstract void draw();
}
Though abstract classes cannot be instantiated, we can create subclasses from it. We can
create objects of subclasses to access members of the abstract class.
Java Abstract Method
We use the same keyword abstract to create abstract methods. An abstract method is
declared without an implementation. For example,
abstract void draw();
It's important to note that, only an abstract class can contain abstract methods. If we include
abstract methods inside a class that is not abstract, we will get an error.
An abstract class can contain both abstract and non-abstract methods.
Inheritance of Abstract Class
An abstract class cannot be instantiated. To access the members of an abstract class, we
must inherit it
Overriding of Abstract Methods
■ In Java, it is mandatory to override abstract methods of the superclass in the subclass. It
is because the subclass inherits abstract methods of the superclass.
■ Since our subclass includes abstract methods, we need to override them.
Why Java Abstraction?
■ Abstraction is an important concept of object-oriented programming. Abstraction only
shows the needed information and all the unnecessary details are kept hidden. 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.