This example shows how to define and use derived types with inheritance and type-bound procedures.
fortranCopy codemodule shapes
implicit none
type :: shape
contains
procedure :: area => shape_area
end type shape
type, extends(shape) :: circle
real :: radius
contains
procedure :: area => circle_area
end type circle
type, extends(shape) :: rectangle
real :: length, width
contains
procedure :: area => rectangle_area
end type rectangle
contains
function shape_area(this) result(area)
class(shape), intent(in) :: this
real :: area
area = 0.0
end function shape_area
function circle_area(this) result(area)
class(circle), intent(in) :: this
real :: area
area = 3.14159 * this%radius**2
end function circle_area
function rectangle_area(this) result(area)
class(rectangle), intent(in) :: this
real :: area
area = this%length * this%width
end function rectangle_area
end module shapes
program test_oop
use shapes
implicit none
type(circle) :: my_circle
type(rectangle) :: my_rectangle
my_circle%radius = 5.0
my_rectangle%length = 4.0
my_rectangle%width = 6.0
print *, 'Circle area: ', my_circle%area()
print *, 'Rectangle area: ', my_rectangle%area()
end program test_oop
Object-Oriented Programming (OOP)