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:
Abstraction allows you to define a "contract" or a template for a group of subclasses. It lets you define some common behavior in the abstract class itself, while forcing subclasses to provide their own implementation for the abstract methods.
This helps to achieve security - hide certain details and only show the important details of an object.
An abstract class can have both abstract and regular methods.
// Abstract class
abstract class Animal {
// Abstract method (does not have a body)
public abstract void animalSound();
// Regular method
public void sleep() {
System.out.println("Zzz");
}
}
// Subclass (inherit from Animal)
class Pig extends Animal {
// The body of animalSound() is provided here
public void animalSound() {
System.out.println("The pig says: wee wee");
}
}
class Main {
public static void main(String[] args) {
// Animal myObj = new Animal(); // will generate an error
Pig myPig = new Pig(); // Create a Pig object
myPig.animalSound();
myPig.sleep();
}
}
In this example:
Animal class.Pig class must implement the animalSound() method, otherwise it would also need to be declared as abstract.Pig object can use both the implemented animalSound() method and the inherited sleep() method.Even though you cannot instantiate an abstract class directly using the new keyword, an abstract class can still have a constructor. This constructor is called when a subclass is instantiated (usually implicitly, or explicitly via super()).
Abstract classes can also contain:
final methods: To provide a fixed implementation that subclasses cannot override.static methods: Utility methods that can be called directly on the abstract class without needing an object.
abstract class Vehicle {
String type;
// Constructor in an abstract class
public Vehicle(String type) {
this.type = type;
System.out.println("Vehicle constructor called. Type: " + type);
}
// Abstract method
public abstract void startEngine();
// Final method (cannot be overridden)
public final void stopEngine() {
System.out.println("Engine stopped safely.");
}
// Static method
public static void serviceRoutine() {
System.out.println("Perform standard 10,000 mile service.");
}
}
class Car extends Vehicle {
public Car() {
// Calling the abstract class constructor
super("Car");
}
@Override
public void startEngine() {
System.out.println("Car engine starting: Vroom!");
}
}
public class Main {
public static void main(String[] args) {
Vehicle.serviceRoutine(); // Call static method directly
Car myCar = new Car(); // Triggers the Vehicle constructor
myCar.startEngine();
myCar.stopEngine(); // Using the final method
}
}
Can you create an object of an abstract class?