On Monday, February 1, 2021 at 8:16:29 AM UTC-8,
arjen.m...@gmail.com wrote:
> A colleague of mine ran into a problem with attempting to use a method from an abstract parent class. The problem is illustrated with this code:
(snip)
> type, extends(parent) :: child
> integer, allocatable, dimension(:) :: z
> contains
> procedure :: alloc => alloc_child
> end type child
I sort-of understand Java abstract classes, so maybe that helps.
In Java, you can not instantiate an abstract class. There are no objects
of that class, only a child of the class.
> contains
> subroutine alloc_child( this, size )
> class(child), intent(inout), target :: this
> integer, intent(in) :: size
>
> !
> ! This fragment does not work:
> !
I think in the Java sense, that you can't have a variable of the
class of an abstract class.
All subclasses would override all methods, or reference the methods
of the abstract class.
> class(parent), pointer :: p
Given that, what happens if you change the above to child instead of parent?
> p => this%parent
> select type (p)
> class is (parent)
> call p%alloc(size)
> end select
And I suspect that since there are no objects of the parent class,
that you can't test for them.
> allocate( this%z(size) )
>
> !
> ! But neither does:
> !
> call this%parent%alloc(size)
> end subroutine alloc_child
>
> end module use_parent
>
> Both Intel Fortran and gfortran complain about the pointer assignment p => and the use of parent%alloc. The error messages are similar, so I am probably do something wrong that should be obvious, but I cannot see what.
Abstract methods are methods that must be overridden by all subclasses.
A class with any abstract method must be abstract, though it can also have
non-abstract methods.
A favorite, if not quite realistic, example is an animal class with the sound method.
There are then subclasses dog, cat, cow, which each implement sound.
In Java, and I presume Fortran, there are methods that are not overridden in the subclass
that are still available to objects of the subclass.