Abstract type: Difference between revisions

From Rosetta Code
Content added Content deleted
No edit summary
Line 16: Line 16:


=={{header|ActionScript}}==
=={{header|ActionScript}}==
While ActionScript does not support explicit abstract classes, it does have interfaces. Interfaces in ActionScript may not implement any methods and all methods are public and implicitly abstract.
While ActionScript does not support explicit abstract classes, it does have interfaces. Interfaces in ActionScript may not implement any methods and all methods are public and implicitly abstract. Interfaces can extend other interfaces, and interfaces may be multiply inherited.
<actionscript>
<actionscript>
package
package

Revision as of 08:26, 8 January 2009

Task
Abstract type
You are encouraged to solve this task according to the task description, using any language you may know.

Abstract type is a type without instances or without definition.

For example in object-oriented programming using some languages, abstract types can be partial implementations of other types, which are to be derived therefrom. An abstract type may provide implementation of some operations and/or components. Abstract types without any implementation are called interfaces. In the languages that do not support multiple inheritance (Ada, Java), classes can, nonetheless, inherit from multiple interfaces. The languages with multiple inheritance (like C++) usually make no distinction between partially implementable abstract types and interfaces. Because the abstract type's implementation is incomplete, OO languages normally prevent instantiation from them (instantiation must derived from one of their descendant classes).

The term abstract datatype also may denote a type, with an implementation provided by the programmer rather than directly by the language (a built-in or an inferred type). Here the word abstract means that the implementation is abstracted away, irrelevant for the user of the type. Such implementation can and should be hidden if the language supports separation of implementation and specification. This hides complexity while allowing the implementation to change without repercussions on the usage. The corresponding software design practice is said to follow the information hiding principle.

It is important not to confuse this abstractness (of implementation) with one of the abstract type. The latter is abstract in the sense that the set of its values is empty. In the sense of implementation abstracted away, all user-defined types are abstract.

In some languages, like for example in Objective Caml which is strongly statically typed, it is also possible to have abstract types that are not OO related and are not an abstractness too. These are pure abstract types without any definition even in the implementation and can be used for example for the type algebra, or for some consistance of the type inference. For example in this area, an abstract type can be used as a phantom type to augment another type as its parameter.

Task: show how an abstract type can be declared in the language. If the language makes a distinction between interfaces and partially implemented types illustrate both.

ActionScript

While ActionScript does not support explicit abstract classes, it does have interfaces. Interfaces in ActionScript may not implement any methods and all methods are public and implicitly abstract. Interfaces can extend other interfaces, and interfaces may be multiply inherited. <actionscript> package {

   public interface IInterface
   {
       function method1():void;
       function method2(arg1:Array, arg2:Boolean):uint;
   }

} </actionscript>

Ada

Interface

Interfaces in Ada may have no components or implemented operation except for ones implemented as null operations. Interfaces can be multiply inherited. <ada> type Queue is limited interface; procedure Enqueue (Lounge : in out Queue; Item : in out Element) is abstract; procedure Dequeue (Lounge : in out Queue; Item : in out Element) is abstract; </ada> Interfaces can be declared synchronized or task when intended implementations are to be provided by protected objects or tasks. For example: <ada> type Scheduler is task interface; procedure Plan (Manager : in out Scheduler; Activity : in out Job) is abstract; </ada>

Abstract type

Abstract types may provide components and implementation of their operations. Abstract types are singly inherited. <ada> with Ada.Finalization; ... type Node is abstract new Ada.Finalization.Limited_Controlled and Queue with record

  Previous : not null access Node'Class := Node'Unchecked_Access;
  Next     : not null access Node'Class := Node'Unchecked_Access;

end record; overriding procedure Finalize (X : in out Node); -- Removes the node from its list if any overriding procedure Dequeue (Lounge : in out Node; Item : in out Element); overriding procedure Enqueue (Lounge : in out Node; Item : in out Element); procedure Process (X : in out Node) is abstract; -- To be implemented </ada> Here Node is an abstract type that is inherited from Limited_Controlled and implements a node of a doubly linked list. It also implements the interface of a queue described above, because any node can be considered a head of the queue of linked elements. For the operation Finalize an implementation is provided to ensure that the element of a list is removed from there upon its finalization. The operation itself is inherited from the parent type Limited_Controlled and then overridden. The operations Dequeue and Enqueue of the Queue interface are also implemented.

C++

You can declare a virtual function to not have an implementation (called "pure virtual function") by the following "= 0" syntax after the method declaration. A class containing at least one pure virtual function (or inheriting one and not overriding it) cannot be instantiated. <cpp>class Abs { public: virtual int method1(double value) = 0; virtual int add(int a, int b){ return a+b; } };</cpp> Because C++ allows multiple inheritance of classes, no distinction is made between interfaces and abstract classes.

Haskell

In Haskell an abstract type is a type class. A type class specifies an interface. One can then define "instances" to provide implementations of the type class for various types.

For example, the built-in type class Eq (the types that can be compared for equality) can be declared as follows:

class  Eq a  where
   (==) :: a -> a -> Bool
   (/=) :: a -> a -> Bool

Default implementations of the functions can be provided:

class  Eq a  where
   (==) :: a -> a -> Bool
   (/=) :: a -> a -> Bool
   x /= y     =  not (x == y)
   x == y     =  not (x /= y)

Here default implementations of each of the operators is circularly defined in terms of the other, for convenience of the programmer; so the programmer only needs to implement one of them for it to work.

Consider the following function which uses the operator == of the type class Eq from above. The arguments to == above were of the unknown type "a", which is of class Eq, so the type of the expression below now must include this restriction:

func :: (Eq a) => a -> Bool
func x = x == x

Suppose I make a new type

data Foo = Foo {x :: Integer, str :: String}

One could then provide an implementation ("instance") the type class Eq with this type

instance Eq Foo where
   (Foo x1 str1) == (Foo x2 str2) =
      (x1 == x2) && (str1 == str2)

And now I can, for example, use the function "func" on two arguments of type Foo.

Java

Methods that don't have an implementation are called abstract methods in Java. A class that contains an abstract method or inherits one but did not override it must be an abstract class; but an abstract class does not need to contain any abstract methods. An abstract class cannot be instantiated. If a method is abstract, it must be public or protected <java>public abstract class Abs { abstract public int method1(double value); abstract protected int method2(String name); int add(int a, int b){ return a+b; } }</java> Interfaces in Java may not implement any methods and all methods are implicitly public and abstract. <java>public interface Inter { int method1(double value); int method2(String name); int add(int a, int b); }</java>

OCaml

Virtual

The equivalent of what is called abstract type in the other OO examples of this page is just called virtual in Objective Caml to define virtual methods and virtual classes:

<ocaml>class virtual foo =

 object
   method virtual bar : int
 end</ocaml>

Abstract Type

In OCaml what we call an abstract type is not OO related, it is only a type defined without definition, for example: <ocaml>type t</ocaml> it is used for example to hide an implementation from the interface of a module or for type algebra.

Example of abstracting a type in an interface: <ocaml>module Foo : sig

 type t

end = struct

 type t = int * int

end</ocaml>

Pure abstract types in the implementation: <ocaml>type u type v type 'a t type ut = u t type vt = v t</ocaml>

PHP

The following is for PHP 5.

Methods that don't have an implementation are called abstract methods in PHP. A class that contains an abstract method or inherits one but did not override it must be an abstract class; but an abstract class does not need to contain any abstract methods. An abstract class cannot be instantiated. If a method is abstract, it must be public or protected <php>abstract class Abs { abstract public function method1($value); abstract protected function method2($name); function add($a, $b){ return a + b; } }</php> Interfaces in PHP may not implement any methods and all methods are public and implicitly abstract. <php>interface Inter { public function method1($value); public function method2($name); public function add($a, $b); }</php>

Python

<python>

  class BaseQueue(object):
      """Abstract/Virtual Class 
      """
      def __init__(self):
          self.contents = list()
          raise NotImplementedError
      def Enqueue(self, item):
          raise NotImplementedError
      def Dequeue(self):
          raise NotImplementedError
      def Print_Contents(self):
          for i in self.contents:
              print i,

</python>

Python allows multiple inheritance and it's more common to implement "mix-in" classes rather than abstract interfaces. (Mix-in classes can implement functionality as well define interfaces).

In this example we're simply following the Python convention of raising the built-in "NotImplementedError" for each function which must be implemented by our subclasses. This is a "purely virtual" class because all of its methods raise the exception. (It is sufficient for __init__ to do so for any partial virtual abstractions since that still ensures that the exception will be raised if anyone attempts to instantiate the base/abstract class directly rather than one of its concrete (fully implemented) descendents).

The method signatures and the instantiation of a "contents" list shown here can be viewed as documentary hints to anyone inheriting from this class. They won't actually do anything in the derived classes (since these methods must be over-ridden therein).

In this case we've implemented one method (Print_Contents). This would be inherited by any derived classes. It could be over-ridden, of course. If it's not over-ridden it establishes a requirement that all derived classes provide some "contents" attribute which must allow for iteration and printing as shown. Without this method the class would be "purely virtual" or "purely abstract." With its inclusion the class becomes "partially implemented."

Note: This "BaseQueue" example should not be confused with Python's standard library Queue class. That is used as the principle "producer/consumer" communications mechanism among threads (and newer multiprocessing processes).


Visual Basic

Abstract Classes

Visual Basic doesn't support abstract classes or implementaiton inheritance.

Interfaces

In Visual Basic, every class is also an interface that other classes can implement. It has this feature because it is based on COM.

Visual Basic .NET

Abstract Classes

  • Overridable means subclasses may change the method's implementation. By default, methods in VB cannot be overridden.
  • MustOverride means the subclasses must provide an implementation
  • By convention all abstract classes have one or more Protected constructors.
MustInherit Class Base

   Protected Sub New()

   End Sub

   Public Sub StandardMethod()
       'code
   End Sub

   Public Overridable Sub Method_Can_Be_Replaced()
       'code
   End Sub

   Public MustOverride Sub Method_Must_Be_Replaced()

End Class

Interfaces

Interfaces may contain Functions, Subroutines, Properties, and Events.

Interface IBase
   Sub Method_Must_Be_Implemented()
End Interface