3.7 クラスインタフェース

クラスインタフェースはクラス定義から自動的に導かれますが、直接定義してクラスの型を制限するのに用いることができます。クラス定義と同じく、クラスインタフェースの定義も新しい型の略記を定義します。

#class type restricted_point_type = 
   object
     method get_x : int
     method bump : unit
 end;;
class type restricted_point_type =
  object method bump : unit method get_x : int end

#fun (x : restricted_point_type) -> x;;
- : restricted_point_type -> restricted_point_type = <fun>
    

プログラムを文書化する目的に加えて、クラスインタフェースはクラスの型を制限するために用いられます。インスタンス変数と、抽象的でないプライベートメソッドはクラス型を制約することにより隠蔽することができます。一方、公開メソッドと抽象メソッドは隠蔽できません。

#class restricted_point' x = (restricted_point x : restricted_point_type);;
class restricted_point' : int -> restricted_point_type
    

もしくは

#class restricted_point' = (restricted_point : int ->restricted_point_type);;
class restricted_point' : int -> restricted_point_type
    

クラスインタフェースはモジュールのシグネチャによって指定することもできます。

#module type POINT = sig 
   class restricted_point' : int ->
     object    
       method get_x : int
       method bump : unit
     end 
 end;;
module type POINT =
  sig
    class restricted_point' :
      int -> object method bump : unit method get_x : int end
  end

#module Point : POINT = struct 
   class restricted_point' = restricted_point
 end;;
module Point : POINT