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:

  1. Animal Class:

    • Abstract Class: Animal
    • Abstract Methods:
      • makeSound()
      • move()

    Subclasses:

    • Dog:
      • makeSound() might return "Woof!" and move() could describe how a dog walks or runs.
    • Cat:
      • makeSound() might return "Meow!" and move() could describe how a cat prowls or jumps.
    • Horse:
      • makeSound() might return "Neigh!" and move() could describe how a horse gallops.
  2. Shape Class:

    • Abstract Class: Shape
    • Abstract Methods:
      • calculateArea()
      • calculatePerimeter()

    Subclasses:

    • Circle:
      • calculateArea() could use the formula for the area of a circle, and calculatePerimeter() could use the formula for the circumference.
    • Rectangle:
      • calculateArea() might be the product of its length and width, and calculatePerimeter() could be the sum of all four sides.
    • Triangle:
      • calculateArea() might use the formula for the area of a triangle, and calculatePerimeter() could be the sum of its three sides.
  3. Employee Class:

    • Abstract Class: Employee
    • Abstract Methods:
      • calculateSalary()
      • displayInfo()

    Subclasses:

    • Manager:
      • calculateSalary() could use the manager's base salary plus bonuses, and displayInfo() might show their management responsibilities and contact details.
    • Developer:
      • calculateSalary() might be based on the developer's hourly rate and hours worked, and displayInfo() could include their programming skills and projects.
    • Salesperson:
      • calculateSalary() might involve a base salary plus commissions, and displayInfo() would include their sales achievements and territories.