About Lesson
Abstract Method is a method that is declared without an implementation. Abstract methods are used in abstract classes, which are classes that cannot be instantiated on their own and are meant to be subclassed. Abstract methods force subclasses to implement these methods.
An abstract method is declared using the abstract
keyword and does not have a body. An abstract method must be declared within an abstract class. Any subclass inheriting an abstract class must implement all its abstract methods, unless the subclass is also abstract.
// Abstract class
abstract class Animal {
// Abstract method (no body)
abstract void makeSound();
// Concrete method
void sleep() {
System.out.println("This animal is sleeping.");
}
}
// Subclass (inherited from Animal)
class Dog extends Animal {
// Providing implementation for abstract method
@Override
void makeSound() {
System.out.println("Woof");
}
}
// Another subclass (inherited from Animal)
class Cat extends Animal {
// Providing implementation for abstract method
@Override
void makeSound() {
System.out.println("Meow");
}
}
public class Main {
public static void main(String[] args) {
Animal myDog = new Dog();
Animal myCat = new Cat();
myDog.makeSound(); // Outputs: Woof
myCat.makeSound(); // Outputs: Meow
myDog.sleep(); // Outputs: This animal is sleeping.
myCat.sleep(); // Outputs: This animal is sleeping.
}
}
Modifiers not allowed for abstract methods
- final
- abstract native
- abstract synchronized
- abstract static
- abstract private
- abstract strictfp