Introduction
Abstraction in Java allows you to hide unnecessary implementation details and show only essential details(information) to the users.
Classes declared using abstract keyword are called Abstract classes in Java and can have both abstract and non-abstract(or concrete) methods.
Rules to Declare an Abstract Class
Here are few rules to declare abstract class listed below.
1) The keyword “abstract” is mandatory.
2) Abstract classes cannot be instantiated(we cannot create objects of abstract classes).
3) An abstract class must have at least one abstract method.
4) An abstract class includes final methods.
5) An abstract class can have both abstract and non-abstract methods.
6) Abstract class can include constructors and static methods.
How to Achieve Abstraction in Java?
Abstraction in Java can be achieved by –
a) Using an Abstract Class
b) Using an Interface
Code to understand a few abstraction rules:
1. We cannot create objects of abstract classes.
//Create an abstract class
abstract class Animal {
// fields and methods
}
…
// try to create an object Animal throws an error
Animal obj = new Animal();
2. An abstract class can have both abstract and non-abstract methods.
abstract class Animal {
// abstract method
abstract void eat();
// concrete method
void bark() {
System.out.println(“This is non-abstract method”);
}
}
3. If a class contains an abstract method, then the class should be declared abstract.
// error
// class should be abstract
class Animal {
// abstract method
abstract void eat();
}
4. Abstract class can include constructors and static methods.
public abstract class Shape {
// static field to access it from a static method
private static String color;
//abstract method
public abstract double area();
//constructor
public Shape(String color) {
this.color = color;
}
//static method
public static void printColor() {
System.out.println(“Color: ” + color);
}
}
class Rectangle extends Shape {
Rectangle() {
super();
…
}
}
Note: 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. However, the super() should always be the first statement of the subclass constructor.
5. An abstract class includes final methods.
abstract class Animal{
// FINAL METHOD
public final void walk(){
System.out.println(“Yes”);
}
public abstract void eat();
}
Note: the final method cannot be abstract itself (other non-final methods, non-abstract methods, or regular methods) in the same class can be).
Real Life Example –
As a computer user, you know that if you press a key on your keyboard, the character associated with that key will be printed on the monitor. However, you do not know what’s happening under the hood – that’s an abstraction.
Don’t judge each day by the harvest you reap but by the seeds that you plant.
Robert Louis Stevenson