Thursday, January 30, 2025
HomeProgrammingAbstract class in Java

Abstract class in Java

In Java, an abstract class is a blueprint for other classes. It acts as a template and cannot be instantiated on its own. Instead, it’s meant to be extended by other classes to provide a common structure while allowing flexibility.

Key Features of Abstract Classes

  1. Definition: Declared using the abstract keyword.
  2. Combination of Methods: Can have both abstract methods (no body, defined using abstract) and regular methods (with implementation).
  3. Cannot Be Instantiated: You can’t create objects of an abstract class.
  4. Supports Inheritance: Allows subclasses to inherit and override its methods.
See also  Regex For String Contains What?

Why Use Abstract Classes?

Abstract classes are ideal when:

  • You want to define common behavior for related classes.
  • Some methods need to be implemented in the base class, while others are specific to subclasses.

Example of an Abstract Class

abstract class Animal {
    // Abstract method (no implementation)
    abstract void sound();

    // Regular method with implementation
    void eat() {
        System.out.println("This animal eats food.");
    }
}

class Dog extends Animal {
    @Override
    void sound() {
        System.out.println("Woof! Woof!");
    }
}

public class Main {
    public static void main(String[] args) {
        Animal myDog = new Dog();
        myDog.sound();
        myDog.eat();
    }
}

Explanation

  1. The Animal class is abstract and has one abstract method, sound(), and one regular method, eat().
  2. The Dog class extends Animal and provides its own implementation of sound().
  3. In the Main class, we create an object of Dog (a subclass of Animal) to call its methods.
See also  How to Make a Dropdown Menu in HTML

When to Use an Abstract Class Over Interfaces?

  • Use abstract classes when classes share common features and you want to provide default functionality.
  • Use interfaces when you want to define a contract or behavior that multiple unrelated classes can implement.
See also  Python String Format () Method

Abstract classes are a powerful feature in Java, offering a balance between structure and flexibility, making your code more organized and easier to maintain.

RELATED ARTICLES
0 0 votes
Article Rating

Leave a Reply

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
- Advertisment -

Most Popular

Recent Comments

0
Would love your thoughts, please comment.x
()
x