Java Inheritance: Circle, Square and Triangle Area Calculation
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
PIdefined 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:
- Polymorphism: a Figura reference pointing to a Circulo object.
- Downcasting: converting a Figura into a Circulo.
- Upcasting: assigning a Triangulo to a Figura variable.
- ArrayList: storing different figures and calling the overridden method on each one.
- 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.