Abstract methods can only exist within an abstract class.
To make a method abstract, use a semicolon (;) instead of the method body.
void talk (); // Abstract method void walk (); // Abstract method
Normal classes can extend the abstract class, but they have to override every abstract method.
You can also create normal methods in the abstract class. And to override normal method is not mandatory.
The abstract class will only complain when you don't override the abstract method.
// Define an abstract class named Person
abstract class Person {
// Abstract method to represent walking behavior
void walk(); // Abstract Method
// Abstract method to represent talking behavior
void talk(); // Abstract Method
}
// Define a concrete class named Jinali which extends Person
class Jinali extends Person {
// Implementing the walk method from the abstract class
@override
void walk() {
print("Jinali can walk");
}
// Implementing the talk method from the abstract class
@override
void talk() {
print("Jinali can talk");
}
}
// Main function, the entry point of the program
void main() {
// Creating an instance of Jinali class
Jinali jinali = new Jinali();
// Calling the talk method of Jinali class
jinali.talk(); // Output: Jinali can talk
// Calling the walk method of Jinali class
jinali.walk(); // Output: Jinali can walk
}
Conclusion:
Abstract Methods are special methods found only in abstract classes.
When a class extends an abstract class, it must provide implementations for all the abstract methods in that class.