25 Oct 2023
Beginner
An abstract method is a method that is declared without an implementation. It is a blueprint for a method that must be implemented in a subclass. Abstract methods are used to define common functionality for a set of related classes.
Examples:
-
Animal Class:
- Abstract Class:
Animal - Abstract Methods:
makeSound()move()
Subclasses:
Dog:makeSound()might return "Woof!" andmove()could describe how a dog walks or runs.
Cat:makeSound()might return "Meow!" andmove()could describe how a cat prowls or jumps.
Horse:makeSound()might return "Neigh!" andmove()could describe how a horse gallops.
- Abstract Class:
-
Shape Class:
- Abstract Class:
Shape - Abstract Methods:
calculateArea()calculatePerimeter()
Subclasses:
Circle:calculateArea()could use the formula for the area of a circle, andcalculatePerimeter()could use the formula for the circumference.
Rectangle:calculateArea()might be the product of its length and width, andcalculatePerimeter()could be the sum of all four sides.
Triangle:calculateArea()might use the formula for the area of a triangle, andcalculatePerimeter()could be the sum of its three sides.
- Abstract Class:
-
Employee Class:
- Abstract Class:
Employee - Abstract Methods:
calculateSalary()displayInfo()
Subclasses:
Manager:calculateSalary()could use the manager's base salary plus bonuses, anddisplayInfo()might show their management responsibilities and contact details.
Developer:calculateSalary()might be based on the developer's hourly rate and hours worked, anddisplayInfo()could include their programming skills and projects.
Salesperson:calculateSalary()might involve a base salary plus commissions, anddisplayInfo()would include their sales achievements and territories.
- Abstract Class:
object-oriented-programming
abstract-method