Interfaces in Ada

In Ada, we can implement interfaces using abstract types and tagged types. Here’s an example of geometric shapes using Ada’s object-oriented features.

with Ada.Text_IO;
with Ada.Numerics;
use Ada.Text_IO;
use Ada.Numerics;

procedure Interfaces is
   -- Define an abstract type for geometric shapes
   type Geometry is abstract tagged null record;

   -- Define abstract methods for the Geometry type
   function Area (Self : Geometry) return Float is abstract;
   function Perim (Self : Geometry) return Float is abstract;

   -- Define a rectangle type
   type Rect is new Geometry with record
      Width, Height : Float;
   end record;

   -- Implement Area and Perim for Rect
   overriding function Area (Self : Rect) return Float is
   begin
      return Self.Width * Self.Height;
   end Area;

   overriding function Perim (Self : Rect) return Float is
   begin
      return 2.0 * Self.Width + 2.0 * Self.Height;
   end Perim;

   -- Define a circle type
   type Circle is new Geometry with record
      Radius : Float;
   end record;

   -- Implement Area and Perim for Circle
   overriding function Area (Self : Circle) return Float is
   begin
      return Pi * Self.Radius * Self.Radius;
   end Area;

   overriding function Perim (Self : Circle) return Float is
   begin
      return 2.0 * Pi * Self.Radius;
   end Perim;

   -- Generic procedure to measure any Geometry object
   procedure Measure (G : Geometry'Class) is
   begin
      Put_Line ("Area: " & Float'Image (G.Area));
      Put_Line ("Perimeter: " & Float'Image (G.Perim));
   end Measure;

   -- Create instances of Rect and Circle
   R : Rect := (Geometry with Width => 3.0, Height => 4.0);
   C : Circle := (Geometry with Radius => 5.0);

begin
   -- Measure the rectangle and circle
   Put_Line ("Rectangle:");
   Measure (R);
   New_Line;
   Put_Line ("Circle:");
   Measure (C);
end Interfaces;

In this Ada example, we define an abstract Geometry type with abstract methods Area and Perim. We then create two concrete types, Rect and Circle, which inherit from Geometry and implement these methods.

The Measure procedure is generic and can work with any type derived from Geometry. This is similar to the concept of interfaces in other languages.

To run this program, save it as interfaces.adb and compile it using an Ada compiler such as GNAT:

$ gnatmake interfaces.adb
$ ./interfaces

The output will show the area and perimeter calculations for both the rectangle and circle.

This example demonstrates how Ada’s object-oriented features can be used to implement interface-like behavior, allowing for polymorphism and code reuse.