Java Inheritance: Circle, Square and Triangle Area Calculation

Computer science1.81 KB

Java Inheritance Example: Geometric Figures

This project demonstrates inheritance, polymorphism, upcasting and downcasting in Java using geometric figures. The abstract class Figura defines the method calcularArea(), which is implemented by the subclasses Circulo, Cuadrado and Triangulo.

Class Figura

  • Abstract class with the protected attribute figura.
  • Constant PI defined as 3.1516.
  • Abstract method calcularArea().

Class Circulo

Calculates the area of a circle using PI * radio^2.

Class Cuadrado

Calculates the area of a square using lado^2.

Class Triangulo

Calculates the area of a triangle using (base * altura) / 2.

Test Programs

TestFigura

Reads the base and height of a triangle, the side of a square and the radius of a circle from the keyboard, then prints the area of each figure.

TestFigura2

Shows the following concepts:

  1. Polymorphism: a Figura reference pointing to a Circulo object.
  2. Downcasting: converting a Figura into a Circulo.
  3. Upcasting: assigning a Triangulo to a Figura variable.
  4. ArrayList: storing different figures and calling the overridden method on each one.
  5. instanceof: identifying the class of each element in the list.

Important Note

The value of PI is defined as 3.1516, which differs from the standard value of Math.PI (3.14159...). Consider using Math.PI for more accurate results.

Download

PDF Word HTML