Abstract class
Abstract class in Java
A class which is declared as abstract is known as an abstract class. It can have abstract and non-abstract methods. It needs to be extended and its method implemented. It cannot be instantiated.
Key Concepts:
Abstract Class:
- An abstract class is declared with the
abstract
keyword (in languages like Java). - It cannot be instantiated directly, meaning you cannot create an object of an abstract class.
- An abstract class is declared with the
Abstract Methods:
- An abstract method is a method that is declared without an implementation (no body).
- It forces subclasses to provide an implementation for this method.
- Abstract methods are also declared using the
abstract
keyword.
Concrete Methods:
- These are regular methods with an implementation.
- An abstract class can have both abstract methods (without implementation) and concrete methods (with implementation).
Purpose of Abstract Class:
Design Blueprint:
- Abstract classes provide a common design for subclasses.
- They define what methods must be implemented by the subclasses.
Code Reusability:
- You can define common methods in the abstract class, which can be shared across multiple subclasses.
- This avoids code duplication and promotes reusability.
Encapsulation:
- Abstract classes help in hiding the implementation details and only exposing the essential features.
- This is part of the OOP principle of encapsulation.
Example in Java:
Here's a simple example to illustrate abstract classes and methods in Java:
// Abstract class
abstract class Animal {
// Concrete method
public void eat() {
System.out.println("This animal eats food.");
}
// Abstract method
public abstract void makeSound();
}
// Subclass (inherits from Animal)
class Dog extends Animal {
// Providing implementation for the abstract method
@Override
public void makeSound() {
System.out.println("The dog barks.");
}
}
// Main class
public class Main {
public static void main(String[] args) {
// Animal animal = new Animal(); // This will give an error because you can't instantiate an abstract class
Animal animal; //declare a reference variable
animal = new Dog();
animal.eat(); // Calls the concrete method from the abstract class
animal.makeSound(); // Calls the implemented abstract method from the subclass
}
}
Comments
Post a Comment