Home  >  Article  >  Java  >  Using abstract classes

Using abstract classes

Linda Hamilton
Linda HamiltonOriginal
2024-09-21 14:17:021096browse

Usando classes abstratas

What is an abstract class?

  • An abstract class serves as a base class that cannot be instantiated directly. It is used to create a generalized form of a class, allowing subclasses to provide specific implementations of some methods.
  • Abstract methods within an abstract class are declared but do not have an implementation in the base class. Subclasses are required to provide concrete implementations.

When to use abstract classes?

  • Use abstract classes when you want to guarantee that certain functionalities are necessarily implemented by subclasses.
  • A common example would be an abstract geometric shape class that provides the signature for an area() method, but leaves the responsibility for defining how to calculate the area to subclasses, such as Triangle and Rectangle.

Implementation with the TwoDShape example:
See example in the Abstraction Package

Code Explanation:
TwoDShape Abstract Class:

  • Defined as abstract because it doesn't make sense to implement area() directly. Each specific geometric shape (like a triangle or rectangle) must provide its own implementation of how to calculate the area.
  • The area() method is declared as abstract, forcing subclasses to implement their version of this method.

Triangle and Rectangle subclasses:

  • Both subclasses inherit from TwoDShape and are required to implement the area() method.
  • Triangle calculates the area with the formula base * height / 2.
  • Rectangle calculates the area with the formula width * height.

AbsShape Class:

  • Demonstrates polymorphism with abstract classes. The area() method is called polymorphically, and the correct version of the method is executed depending on the object type (Triangle or Rectangle).

The above is the detailed content of Using abstract classes. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn