allthingsare๐Ÿ…ฟ๏ธ.com Books โฌ…๏ธ Back allthingsare

โ€œWhether you think you can or you think you canโ€™t, youโ€™re right.โ€
[Henry Ford (1863โ€“1947) โ€“ American industrialist, founder of Ford Motor Company]


What is an Abstract Class


13.1.1 What is Abstraction?

Abstraction is another core pillar of object-oriented programming (OOP).
It means showing only the essential features of an object and hiding the complex implementation details.

In Java, abstract classes are one way to implement this idea.
An abstract class is a class that cannot be instantiated directly โ€” it acts as a template for other classes.
It may contain:

  • Abstract methods: declared without a body โ€” the child class must provide the implementation.

  • Concrete methods: normal methods with full code.

  • Fields: variables that can be inherited by child classes.


Why use an abstract class?

  • To define a common blueprint for multiple subclasses.

  • To enforce that certain methods must be implemented by the child class.

  • To share common code while still keeping some parts flexible.


13.1.2 How to Declare an Abstract Class

You declare an abstract class using the abstract keyword.

Example:

java
public abstract class Animal { String name; abstract void makeSound(); // no body โ€” must be implemented by child void sleep() { System.out.println(name + " is sleeping."); } }

Key points:

  • Animal cannot be instantiated directly: new Animal() โ†’ compiler error!

  • makeSound() is abstract โ€” child classes must override it.

  • sleep() is a normal method โ€” child classes inherit it as-is.


13.1.3 Mini Lab: Abstract Class in Action

Letโ€™s see how to use an abstract class:

java
public abstract class Animal { String name; abstract void makeSound(); void sleep() { System.out.println(name + " is sleeping."); } } public class Dog extends Animal { @Override void makeSound() { System.out.println(name + " says: Woof!"); } public static void main(String[] args) { Dog d = new Dog(); d.name = "Buddy"; d.makeSound(); d.sleep(); } }

How it works:

  • Dog inherits sleep() as-is.

  • Dog must implement makeSound().

  • Animal defines the blueprint, Dog fills in the details.


Key benefit:
Abstract classes help you design general contracts with flexible implementations.