Abstract type: Difference between revisions

m (→‎{{header|Phix}}: added syntax colouring the hard way)
imported>Regattaguru
(30 intermediate revisions by 17 users not shown)
Line 14:
'''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.
 
 
{{omit from|MiniZinc|no ability to declare new types at all}}
=={{header|11l}}==
You can declare a virtual function to not have an implementation by using <code>F.virtual.abstract</code> keyword. A type containing at least one abstract virtual function cannot be instantiated.
<syntaxhighlight lang="11l">T AbstractQueue
F.virtual.abstract enqueue(Int item) -> N
 
T PrintQueue(AbstractQueue)
F.virtual.assign enqueue(Int item) -> N
print(item)</syntaxhighlight>
 
=={{header|AArch64 Assembly}}==
{{omit from|AArch64 Assembly}}
 
=={{header|ABAP}}==
=== Abstract Class ===
<langsyntaxhighlight ABAPlang="abap">class abs definition abstract.
public section.
methods method1 abstract importing iv_value type f exporting ev_ret type i.
Line 33 ⟶ 40:
ev_ret = iv_a + iv_b.
endmethod.
endclass.</langsyntaxhighlight>
 
=== Interfaces ===
Line 40 ⟶ 47:
2. Variables must be static final. The values may be computed at run time.
3. No static initialiser blockers. No static initialiser helper methods.
<langsyntaxhighlight ABAPlang="abap">interface inter.
methods: method1 importing iv_value type f exporting ev_ret type i,
method2 importing iv_name type string exporting ev_ret type i,
add importing iv_a type i iv_b type i exporting ev_ret type i.
endinterface.</langsyntaxhighlight>
 
=={{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. Interfaces can extend other interfaces, and interfaces may be multiply inherited.
<langsyntaxhighlight lang="actionscript">package
{
public interface IInterface
Line 55 ⟶ 62:
function method2(arg1:Array, arg2:Boolean):uint;
}
}</langsyntaxhighlight>
 
Abstract types can also be simulated using the built-in <code>flash.utils.getQualifiedClassName()</code> function in the constructor to check that the runtime type is an inhertied class, and throwing exceptions from "abstract" methods which can be overridden by inheritors to disable them. If any inheriting class does not implement an abstract method, the error will not be thrown until the non-implemented method is called.
<syntaxhighlight lang="actionscript">
<lang ActionScript>
package {
import flash.utils.getQualifiedClassName;
Line 81 ⟶ 88:
}
}
</syntaxhighlight>
</lang>
 
Inheriting this class:
<syntaxhighlight lang="actionscript">
<lang ActionScript>
package {
 
Line 95 ⟶ 102:
}
}
</syntaxhighlight>
</lang>
 
=={{header|Ada}}==
===Interface===
Interfaces in [[Ada]] may have no components or implemented operation except for ones implemented as null operations. Interfaces can be multiply inherited.
<langsyntaxhighlight lang="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;</langsyntaxhighlight>
Interfaces can be declared synchronized or task when intended implementations are to be provided by protected objects or [[task]]s. For example:
<langsyntaxhighlight lang="ada">type Scheduler is task interface;
procedure Plan (Manager : in out Scheduler; Activity : in out Job) is abstract;</langsyntaxhighlight>
===Abstract type===
Abstract types may provide components and implementation of their operations. Abstract types are singly inherited.
<langsyntaxhighlight lang="ada">with Ada.Finalization;
...
type Node is abstract new Ada.Finalization.Limited_Controlled and Queue with record
Line 117 ⟶ 124:
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</langsyntaxhighlight>
Here Node is an abstract type that is inherited from Limited_Controlled and implements a node of a [[Doubly-Linked List (element) | 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.
 
Line 123 ⟶ 130:
Using [http://wiki.portal.chalmers.se/agda/agda.php?n=ReferenceManual.Records records] for storing the interface methods and [http://wiki.portal.chalmers.se/agda/pmwiki.php?n=ReferenceManual.InstanceArguments instance arguments] (which are [http://wiki.portal.chalmers.se/agda/pmwiki.php?n=ReferenceManual.ModellingTypeClassesWithInstanceArguments similar] to Haskell type classes) for overloading:
 
<langsyntaxhighlight lang="agda">module AbstractInterfaceExample where
 
open import Function
Line 175 ⟶ 182:
-- say (cat crazy!) => "meeeoooowwwww!!!"
-- say (cat plain-cat) => "meow!"
-- </langsyntaxhighlight>
 
There is <code>dog</code> and <code>cat</code> is objects of different types for which the interface method is implemented.
Line 182 ⟶ 189:
An abstract class contains functions that have no body defined. You cannot instantiate a class that contains abstract functions.
 
<langsyntaxhighlight lang="aikido">class Abs {
public function method1...
public function method2...
 
}</langsyntaxhighlight>
Interfaces in Aikido define a set of functions, operators, classes, interfaces, monitors or threads (but no variables) that must be implemented by a class implementing the interface.
<langsyntaxhighlight lang="aikido">interface Inter {
function isFatal : integer
function operate (para : integer = 0)
operator -> (stream, isout)
}</langsyntaxhighlight>
 
=={{header|AmigaE}}==
In AmigaE, abstract methods are supported but interfaces are not.
 
<langsyntaxhighlight lang="amigae">
OBJECT fruit
ENDOBJECT
Line 217 ⟶ 224:
FORALL({x},[NEW a, NEW o],`x.color())
ENDPROC
</syntaxhighlight>
</lang>
prints to the console:
 
Line 223 ⟶ 230:
 
=={{header|Apex}}==
<langsyntaxhighlight lang="apex">
// Interface
public interface PurchaseOrder {
Line 247 ⟶ 254:
public override Integer abstractMethod() { return 5; }
}
</syntaxhighlight>
</lang>
 
=={{header|Argile}}==
{{works with|Argile|1.0.0}}
<langsyntaxhighlight Argilelang="argile">use std
 
(: abstract class :)
Line 288 ⟶ 295:
foobar (new Sub 34) (: prints 46 :)
foobar (new Sub) (: prints 11 :)
foobar (new Abs) (: prints 0 :)</langsyntaxhighlight>
 
 
{{omit from|ARM Assembly}}
 
=={{header|AutoHotkey}}==
{{works with | AutoHotkey_L}}
<langsyntaxhighlight AutoHotkeylang="autohotkey">color(r, g, b){
static color
If !color
Line 323 ⟶ 329:
msgbox % blue.GetRGB() ; displays 255
return
</syntaxhighlight>
</lang>
 
=={{header|BBC BASIC}}==
==={{header|BBC BASIC}}===
{{works with|BBC BASIC for Windows}}
BBC BASIC is a procedural language with no built-in OO features. The CLASSLIB library implements simple Object Classes with multiple inheritance; an abstract class may be created without any instantiation, the sole purpose of which is for other classes to inherit from it. At least one member or method must be declared, but no error will be generated if there is no implementation:
<langsyntaxhighlight lang="bbcbasic"> INSTALL @lib$+"CLASSLIB"
REM Declare a class with no implementation:
Line 346 ⟶ 353:
REM Test by calling the method:
PROC(instance.method)</langsyntaxhighlight>
==={{header|QB64}}===
QB64, along with QBasic and QuickBasic (without extension), is not Object-Oriented; however, the following addresses issues raised in the description of the problem as well as the problem itself:
<syntaxhighlight lang="qb64">'Keep in mind that this code DOES NOT follow appropriate coding structure, but is used for easiest explanation. That
'said, the following is both legal and executable.
 
a = 15 'Addressing the point raised regarding hiding complexity from the programmer, QB64 follows the QBasic/QuickBasic paradigm
'of not requiring the programmer to declare the type of a variable at all. In fact, variables can be used without any prior
'declaration or DIMensioning. So, in this way an undeclared variable is somewhat similar to a VOID in C/C++; however,
'unlike a VOID, the undeclared variable in QB64 DOES have a type, but the programmer need not be concerned with what it is.
 
Type c 'The closest to having Classes QB64 comes, being not OO, is user-defined types, which are containers of multiple
'values of same or different types. This is a declaration of a user-defined type named "c" which has the
'following elements:
d As Integer 'This is the declaration of variable "d", which is an element (notice the lack of the use of the word "member") of
'the user-defined type "c".
e As String 'As mentioned above the user-defined type, in this case "c", can have constituent elements of differing types.
End Type 'Notice that since this is a user-defined type and not an object, there are no methods defined within it. For this
'example defining a member of "c" as both a SUBroutine and a FUNCTION was attempted, neither of which was
'successful. It should also be noted that it is illegal to define a user-defined type without any elements. Put
'another way, all user-defined types require at least one element.
 
 
Type f 'As QB64 is not OO, it does not have true inheritence; however, the nesting of user-defined types is allowed, which
'allows for an attempt at inheritance, as close as QB64 can come. As well as pseudo-abstracting the type "c", which
'need not ever be directly accessed, although since instantiation occurs at declaration, memory allocation is most
'likely made for it.
g As c 'This is the declaration of a user-defined type as an element of another user-defined type. If "c" were used
'nowhere else in the program, but only here as a variable type, the pseudo-abstraction is achieved.
h As Integer
End Type
 
c.d = 25 'This is the way in which elements of user-defined types are accessed. Here the type "c" has been directly accessed
'and thus eliminates any such pseudo-abstraction as mentioned above.
 
Dim i As f 'This is the declaration of a variable of the user-defined type "f", which allows for the following.
i.g.e = "thirty five" 'This is the way in which the element of a user-define type containing another user-defined type as an
'element is access. In this way, user-defined type "f" has been pseudo-abstracted since its elements are
'never directly referenced in the rest of this program, even though memory has been allocated for it and its
'constituent elements.
Dim j As f 'This is a second instance of the user-defined type "f", showing that "f" has been pseudo-abstracted, even
'though "f" does exist in its own right in memory.
j.g.e = "forty five"
 
Print a
Print b
Print c.d
Print c.e
Print i.g.e 'This is another use of the previously declared variable "i" and its element "g"'s element "e".
Print g.e 'This is NOT a use of the above variable "i" or any of its elements. Since QB64 does not require strict typing
'nor contain a typeOf() function, it is unclear of what type "g.e" is, although it is suspected that it is either
'an Integer or a String, being a use of type "c"'s element "d" or "e".
Print j.g.e
System </syntaxhighlight>
{{out}}
<pre>15
0
25
0
thirty five
0
forty five</pre>
 
==={{header|QBasic}}===
{{works with|QBasic|1.1}}
{{works with|QuickBasic|4.5}}
{{trans|QB64}}
<syntaxhighlight lang="qbasic">a = 15
TYPE c
d AS INTEGER
e AS STRING * 12
END TYPE
c.d = 25
 
TYPE f
g AS c
h AS INTEGER
END TYPE
DIM i AS f
i.g.e = "thirty five"
 
DIM j AS f
j.g.e = "forty five"
 
PRINT a
PRINT b
PRINT c.d
PRINT c.e
PRINT i.g.e
PRINT g.e
PRINT j.g.e</syntaxhighlight>
 
 
=={{header|C}}==
Line 352 ⟶ 452:
 
The header file for the abstract class, interfaceAbs.h
<langsyntaxhighlight lang="c">#ifndef INTERFACE_ABS
#define INTERFACE_ABS
 
Line 384 ⟶ 484:
do { if (c) { free((c)->instData); free(c); } } while(0);
#endif</langsyntaxhighlight>
That will define the abstract class. The next section declares a public interface for a class providing the interface of the abstract class. This class is Silly and
the code is in file silly.h. Note the actual structure of the class is not provided
here. We don't want it visible.
<langsyntaxhighlight lang="c">#ifndef SILLY_H
#define SILLY_H
#include "intefaceAbs.h"
Line 397 ⟶ 497:
extern AbsCls Silly_Instance(void *);
 
#endif</langsyntaxhighlight>
Ok. Now it is necessary to provide the implementation of the realizable class.
This code should be in silly.c.
<langsyntaxhighlight lang="c">#include "silly.h"
#include <string.h>
#include <stdio.h>
Line 440 ⟶ 540:
}
 
ABSTRACT_METHODS( Silly, MyMethod1, MyMethod2, MyMethod3)</langsyntaxhighlight>
That last macro, ABSTRACT_METHODS may need a little explanation. First note that macros do a string substitution of the parameter values into the arguments of the defined macro, with a little hitch. In the macro definition the ' ## ' expression is special. Here cName ## _Iface gets converted to Silly_Iface, as 'Silly' replaces cName. So the macro call declares an instance of the class record, and defines a constructor named Silly_Instance, which takes a Silly structure as an arguments
and uses the class record it previously set up as well.
Line 447 ⟶ 547:
 
Now all's left is some example code that uses all this stuff.
<langsyntaxhighlight lang="c">#include <stdio.h>
#include "silly.h"
 
Line 460 ⟶ 560:
return 0;
}
</syntaxhighlight>
</lang>
 
=={{header|C sharp|C#}}==
<langsyntaxhighlight lang="csharp">abstract class Class1
{
public abstract void method1();
Line 471 ⟶ 571:
return 0;
}
}</langsyntaxhighlight>
 
=={{header|C++}}==
You can declare a virtual function to not have an implementation (called "pure virtual function") by the following "<tt>= 0</tt>" syntax after the method declaration. A class containing at least one pure virtual function (or inheriting one and not overriding it) cannot be instantiated.
<langsyntaxhighlight lang="cpp">class Abs {
public:
virtual int method1(double value) = 0;
Line 481 ⟶ 581:
return a+b;
}
};</langsyntaxhighlight>
Because C++ allows multiple inheritance of classes, no distinction is made between interfaces and abstract classes.
 
Line 488 ⟶ 588:
In Caché, abstract and data type classes cannot be instantiated directly - there must be a 'concrete subclass' that extends them as well as the '%RegisteredObject' class in order to instantiate an object, see example below.
 
<langsyntaxhighlight lang="cos">Class Abstract.Class.Shape [ Abstract ]
{
Parameter SHAPE = 1;
Line 502 ⟶ 602:
Write ..%ClassName()_$Case(..%Extends(..%PackageName()_".Shape"), 1: " is a ", : " is not a ")_"shape"
}
}</langsyntaxhighlight>
 
Data type classes differ because they cannot contain properties, see example below.
 
<langsyntaxhighlight lang="cos">Class Abstract.DataType.Shape [ ClassType = datatype ]
{
Parameter SHAPE = 1;
Line 519 ⟶ 619:
Write ..%ClassName()_$Case(..%Extends(..%PackageName()_".Shape"), 1: " is a ", : " is not a ")_"shape"
}
}</langsyntaxhighlight>
 
Both class types can contain implementation code. Caché allows multiple inheritance of classes, so no distinction is made between abstract classes and interfaces.
Line 538 ⟶ 638:
Using defprotocol, we can define what is essentially an interface.
 
<langsyntaxhighlight lang="lisp">(defprotocol Foo (foo [this]))</langsyntaxhighlight>
 
=={{header|COBOL}}==
===Interface===
{{trans|F#}}
<langsyntaxhighlight lang="cobol"> INTERFACE-ID.IDENTIFICATION ShapeDIVISION.
INTERFACE-ID. Shape.
PROCEDURE DIVISION.
IDENTIFICATION DIVISION.
METHOD-ID. perimeter.
DATA DIVISION.
Line 554 ⟶ 656:
END METHOD perimeter.
IDENTIFICATION DIVISION.
METHOD-ID. shape-area.
DATA DIVISION.
Line 564 ⟶ 667:
 
IDENTIFICATION DIVISION.
CLASS-ID. Rectangle.
Line 571 ⟶ 675:
INTERFACE Shape.
IDENTIFICATION DIVISION.
OBJECT IMPLEMENTS Shape.
DATA DIVISION.
Line 579 ⟶ 684:
PROCEDURE DIVISION.
IDENTIFICATION DIVISION.
METHOD-ID. perimeter.
DATA DIVISION.
Line 584 ⟶ 690:
01 ret USAGE FLOAT-LONG.
PROCEDURE DIVISION RETURNING ret.
COMPUTE ret = width * 2.0 + height * 2.0
GOBACK ret = width * 2.0 + height * 2.0
.END-COMPUTE
GOBACK.
END METHOD perimeter.
IDENTIFICATION DIVISION.
METHOD-ID. shape-area.
DATA DIVISION.
Line 594 ⟶ 702:
01 ret USAGE FLOAT-LONG.
PROCEDURE DIVISION RETURNING ret.
COMPUTE ret = width * height
GOBACK ret = width * height
.END-COMPUTE
GOBACK.
END METHOD shape-area.
END OBJECT.
END CLASS Rectangle.</langsyntaxhighlight>
 
=={{header|Common Lisp}}==
Line 606 ⟶ 716:
In Common Lisp, classes do not implement methods, but methods specialized for particular kinds of arguments may be defined for generic functions. Since we can programmatically determine whether methods are defined for a list of arguments, we can simulate a kind of abstract type. We define an abstract type <code>kons</code> to which an object belongs if methods for <code>kar</code> and <code>kdr</code> are defined for it. We define a type predicate <code>konsp</code> and a type <code>kons</code> in terms of the type predicate.
 
<langsyntaxhighlight lang="lisp">(defgeneric kar (kons)
(:documentation "Return the kar of a kons."))
 
Line 618 ⟶ 728:
 
(deftype kons ()
'(satisfies konsp))</langsyntaxhighlight>
 
We can make the built-in types <code>cons</code> and <code>integer</code> <code>kons</code>es. We start with <code>cons</code>, using the obvious definitions.
 
<langsyntaxhighlight lang="lisp">(defmethod kar ((cons cons))
(car cons))
 
Line 631 ⟶ 741:
(typep (cons 1 2) 'kons) ; => t
(kar (cons 1 2)) ; => 1
(kdr (cons 1 2)) ; => 2</langsyntaxhighlight>
 
For integers, we'll define the <code>kar</code> of <var>n</var> to be <var>1</var> and the <code>kdr</code> of <var>n</var> to be <var>n - 1</var>. This means that for an integer <var>n</var>, <var>n</var> = <code>(+ (kar <var>n</var>) (kdr <var>n</var>))</code>.
 
<langsyntaxhighlight lang="lisp">(defmethod kar ((n integer))
1)
 
Line 645 ⟶ 755:
(typep 45 'kons) ; => t
(kar 45) ; => 1
(kdr 45) ; => 44</langsyntaxhighlight>
 
=={{header|Component Pascal}}==
<langsyntaxhighlight lang="oberon2">
(* Abstract type *)
Object = POINTER TO ABSTRACT RECORD END;
Line 660 ⟶ 770:
x,y: REAL
END;
</syntaxhighlight>
</lang>
...
<langsyntaxhighlight lang="oberon2">
(* Abstract method of Object *)
PROCEDURE (dn: Object) Show*, NEW, ABSTRACT;
Line 678 ⟶ 788:
StdLog.Real(p.y);StdLog.String(");");StdLog.Ln
END Show;
</syntaxhighlight>
</lang>
 
For usage see tasks Stacks.
 
=={{header|Crystal}}==
<langsyntaxhighlight lang="ruby">abstract class Animal # only abstract class can have abstract methods
abstract def move
abstract def think
Line 722 ⟶ 832:
# Animal.new # => can't instantiate abstract class
he = Human.new("Andrew") # ok
he.process</langsyntaxhighlight>
Note that "class" can be replaced with "struct" in the above example, because Crystal also supports abstract structs and their inheritance.
 
=={{header|D}}==
<langsyntaxhighlight lang="d">import std.stdio;
 
class Foo {
Line 752 ⟶ 862:
}
 
void main() {}</langsyntaxhighlight>
 
=={{header|Delphi}}==
Abstract Class introduced in Delphi 2006. An abstract class cannot be instantiated and must be derived from in order to be used.
 
<langsyntaxhighlight lang="delphi">TSomeClass = class abstract (TObject)
...
end;</langsyntaxhighlight>
 
 
Abstract Methods can only be implemented in derived classes. A concrete class that contains abstract methods can be instantiated. A warning will be generated at compile time, and an EAbstractError exception will thrown if the method is called at run time.
 
<langsyntaxhighlight lang="delphi">type
TMyObject = class(TObject)
public
Line 776 ⟶ 886:
begin
AbstractFunction; // Calling the abstract function
end;</langsyntaxhighlight>
 
=={{header|DWScript}}==
Line 790 ⟶ 900:
A simple abstract type without enforcement can be created using the interface expression:
 
<langsyntaxhighlight lang="e">interface Foo {
to bar(a :int, b :int)
}</langsyntaxhighlight>
 
With enforcement, a separate ''stamp'' is created which must be applied to the instances. This is analogous to a Java interface.
 
<langsyntaxhighlight lang="e">interface Foo guards FooStamp {
to bar(a :int, b :int)
}
Line 804 ⟶ 914:
return a - b
}
}</langsyntaxhighlight>
 
=={{header|Eiffel}}==
 
<syntaxhighlight lang="eiffel">
<lang Eiffel>
deferred class
AN_ABSTRACT_CLASS
Line 826 ⟶ 936:
 
end
</syntaxhighlight>
</lang>
 
A more expressive view of an Abstract type in Eiffel:
<langsyntaxhighlight lang="eiffel">
note
title: "Prototype Person"
Line 891 ⟶ 1,001:
 
end
</syntaxhighlight>
</lang>
=={{header|Elena}}==
 
<langsyntaxhighlight lang="elena">abstract class Bike
{
abstract run();
}
</syntaxhighlight>
</lang>
 
=={{header|EMal}}==
{{trans|Go}}
<syntaxhighlight lang="emal">
^|EMal does not support abstract types with partial implementations,
|but can use interfaces.
|^
type Beast
interface
fun getKind = text by block do end
fun getName = text by block do end
fun getCry = text by block do end
end
type Dog implements Beast
model
text kind
text name
fun getKind = text by block do return me.kind end
fun getName = text by block do return me.name end
fun getCry = text by block do return "Woof" end
end
type Cat implements Beast
model
text kind
text name
fun getKind = text by block do return me.kind end
fun getName = text by block do return me.name end
fun getCry = text by block do return "Meow" end
end
type AbstractType
^|Beast b = Beast() # interface instantiation is not allowed|^
fun bprint = void by Beast b
writeLine(b.getName() + ", who's a " + b.getKind() + ", cries: " + b.getCry() + ".")
end
^|instantiation works because a positional variadic constructor
|has been auto generated
|^
var d = Dog("labrador", "Max")
Cat c = Cat("siamese", "Sammy")
bprint(d)
bprint(c)
</syntaxhighlight>
{{out}}
<pre>
Max, who's a labrador, cries: Woof.
Sammy, who's a siamese, cries: Meow.
</pre>
 
=={{header|F Sharp|F#}}==
A type with only abstract members and without constructors is an '''interface''' (when not marked with the <code>AbstractClass</code> attribute). Example:
<langsyntaxhighlight lang="fsharp">type Shape =
abstract Perimeter: unit -> float
abstract Area: unit -> float
Line 909 ⟶ 1,066:
interface Shape with
member x.Perimeter() = 2.0 * width + 2.0 * height
member x.Area() = width * height</langsyntaxhighlight>
 
A type that leaves some or all members unimplemented, is an '''abstract class'''. It has to be marked with the <code>AbstractClass</code> attribute. Example:
<langsyntaxhighlight lang=" fsharp">[<AbstractClass>]
type Bird() =
// an abstract (=virtual) method with default impl.
Line 927 ⟶ 1,084:
inherit Bird()
override x.Move() = printfn "walking"
override x.Sing() = "hiss hiss!"</langsyntaxhighlight>
 
=={{header|Fantom}}==
<langsyntaxhighlight lang="fantom">
abstract class X
{
Line 959 ⟶ 1,116:
}
}
</syntaxhighlight>
</lang>
 
=={{header|Forth}}==
Line 965 ⟶ 1,122:
{{trans|Fantom}}
There are numerous, mutually incompatible object oriented frameworks for Forth. This one works with the FOOS preprocessor extension of [[4tH]].
<langsyntaxhighlight lang="forth">include 4pp/lib/foos.4pp
 
:: X()
Line 989 ⟶ 1,146:
;
 
Main</langsyntaxhighlight>
 
Works with any ANS Forth
Line 995 ⟶ 1,152:
Needs the FMS-SI (single inheritance) library code located here:
http://soton.mpeforth.com/flag/fms/index.html
<langsyntaxhighlight lang="forth">include FMS-SI.f
 
The FMS object extension uses duck typing and so has no need for abstract types.
</syntaxhighlight>
</lang>
 
=={{header|Fortran}}==
Simple abstract derived type (i.e. abstract class) in Fortran 2008
<langsyntaxhighlight lang="fortran">
! abstract derived type
type, abstract :: TFigure
Line 1,019 ⟶ 1,176:
end function calculate_area
end interface
</syntaxhighlight>
</lang>
 
=={{header|FreeBASIC}}==
Line 1,026 ⟶ 1,183:
However, you can effectively create an abstract type by declaring all its methods to be abstract, so that they do not require a body in the declaring type itself. Such methods can then be overridden and implemented by its derived types. For example :-
<langsyntaxhighlight lang="freebasic">' FB 1.05.0 Win64
 
Type Animal Extends Object
Line 1,068 ⟶ 1,225:
Print
Print "Press any key to quit program"
Sleep</langsyntaxhighlight>
 
{{out}}
Line 1,078 ⟶ 1,235:
=={{header|Genyris}}==
In Genyris by default there are no constructors. In effect all classes are Abstract until they are used to tag (describe) an object. This in keeping with the language's roots in Description Logic. To prevent the class ever being associated with an instance it suffices to force the validator to fail.
<langsyntaxhighlight lang="genyris">class AbstractStack()
def .valid?(object) nil
 
tag AbstractStack some-object # always fails</langsyntaxhighlight>
 
However this is not much use if we want to use an abstract class to define an '''interface'''. Here is a quasi-abstract class which can be used to tag objects if they conform to the class's membership expectations. In this case it wants two methods, ''.enstack'' and ''.destack'':
<langsyntaxhighlight lang="genyris">class StackInterface()
def .valid?(object)
object
Line 1,091 ⟶ 1,248:
is-instance? .enstack Closure
bound? .destack
is-instance? .destack Closure</langsyntaxhighlight>
 
So if ever we find an object which conforms to the validator it can be tagged. Here's a 'traditional' class definition using the Object class which ''does'' provide a constructor:
<langsyntaxhighlight lang="genyris">class XYZstack(Object)
def .init()
var .items ()
Line 1,102 ⟶ 1,259:
var tmp (car .items)
setq .items (cdr .items)
tmp</langsyntaxhighlight>
Now we can tag an object that conforms to the Interface:
<langsyntaxhighlight lang="genyris">tag StackInterface (XYZstack(.new))</langsyntaxhighlight>
 
=={{header|Go}}==
Line 1,113 ⟶ 1,270:
In the following example, the Dog and Cat types both satisfy the Beast interface because they each have the specified methods. The ''bprint'' function can print details for any Beast.
 
<langsyntaxhighlight lang="go">package main
 
import "fmt"
Line 1,154 ⟶ 1,311:
bprint(d)
bprint(c)
}</langsyntaxhighlight>
 
{{out}}
Line 1,166 ⟶ 1,323:
 
As in [[Java]], methods that are declared but not implemented are called "abstract" methods. An interface is a class-level typing construct that can only contain abstract method declarations (well, and constants, but pay no attention to those).
<langsyntaxhighlight lang="groovy">public interface Interface {
int method1(double value)
int method2(String name)
int add(int a, int b)
}</langsyntaxhighlight>
 
An abstract class may implement some of its methods and leave others unimplemented. The unimplemented methods and the class itself must be declared "abstract".
<langsyntaxhighlight lang="groovy">public abstract class Abstract1 {
abstract public int methodA(Date value)
abstract protected int methodB(String name)
int add(int a, int b) { a + b }
}</langsyntaxhighlight>
 
An abstract class may also be used to partially implement an interface. Here class "Abstract2" implements the "add" method from the inherited "Interface", but leaves the other two methods, "method1" and "method2", unimplemented. Abstract methods that an abstract class inherits from an interface or another abstract class do not have to be redeclared.
<langsyntaxhighlight lang="groovy">public abstract class Abstract2 implements Interface {
int add(int a, int b) { a + b }
}</langsyntaxhighlight>
 
Interfaces and abstract classes cannot be instantiated directly. There must be a "concrete subclass" that contains a complete implementation in order to instantiate an object.
<langsyntaxhighlight lang="groovy">public class Concrete1 implements Interface {
public int method1(double value) { value as int }
public int method2(String name) { (! name) ? 0 : name.toList().collect { it as char }.sum() }
Line 1,199 ⟶ 1,356:
public int method1(double value) { value as int }
public int method2(String name) { (! name) ? 0 : name.toList().collect { it as char }.sum() }
}</langsyntaxhighlight>
 
Notice that there are no extra descriptive keywords on the interface method declarations. Interface methods are assumed to be both abstract and public.
 
Obligatory test:
<langsyntaxhighlight lang="groovy">def c1 = new Concrete1()
assert c1 instanceof Interface
println (new Concrete1().method2("Superman"))
Line 1,215 ⟶ 1,372:
assert c3 instanceof Interface
assert c3 instanceof Abstract2
println (new Concrete3().method2("Hellboy"))</langsyntaxhighlight>
 
Obligatory test output:
Line 1,229 ⟶ 1,386:
 
For example, the built-in type class Eq (the types that can be compared for equality) can be declared as follows:
<langsyntaxhighlight lang="haskell">class Eq a where
(==) :: a -> a -> Bool
(/=) :: a -> a -> Bool</langsyntaxhighlight>
 
Default implementations of the functions can be provided:
<langsyntaxhighlight lang="haskell">class Eq a where
(==) :: a -> a -> Bool
(/=) :: a -> a -> Bool
x /= y = not (x == y)
x == y = not (x /= y)</langsyntaxhighlight>
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:
<langsyntaxhighlight lang="haskell">func :: (Eq a) => a -> Bool
func x = x == x</langsyntaxhighlight>
 
Suppose I make a new type
<langsyntaxhighlight lang="haskell">data Foo = Foo {x :: Integer, str :: String}</langsyntaxhighlight>
 
One could then provide an implementation ("instance") the type class Eq with this type
<langsyntaxhighlight lang="haskell">instance Eq Foo where
(Foo x1 str1) == (Foo x2 str2) =
(x1 == x2) && (str1 == str2)</langsyntaxhighlight>
And now I can, for example, use the function "func" on two arguments of type Foo.
 
Line 1,259 ⟶ 1,416:
An abstract class is a class with abstract methods. Icon is not object-oriented.
 
<langsyntaxhighlight lang="unicon">class abstraction()
abstract method compare(l,r) # generates runerr(700, "method compare()")
end</langsyntaxhighlight>
 
=={{header|J}}==
Line 1,275 ⟶ 1,432:
 
=={{header|Java}}==
Java has an <code>interface</code> and an <code>abstract class</code>. Neither of which can be instantiated, and require some sort of implementation or abstraction.<br />
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 cannot be private.
For an <code>interface</code>, only the <code>private</code> and <code>default</code> access modifiers are allowed, which also implies they require code.<br />
A <code>private</code> method cannot be overridden by a sub-class, and a <code>default</code> method, optionally, can.<br />
A method with no access modifier is inherently <code>public</code>, must not contain code, and requires implementation by its sub-class.<br />
Member fields are allowed, although are effectively <code>public</code>, <code>final</code>, and <code>static</code>, thus requiring a value.<br />
Here is an example of an <code>interface</code>.
<syntaxhighlight lang="java">
interface Example {
String stringA = "rosetta";
String stringB = "code";
 
private String methodA() {
<lang java>public abstract class Abs {
return stringA + " " + stringB;
public abstract int method1(double value);
protected abstract int method2(String name);
int add(int a, int b) {
return a + b;
}
 
}</lang>
default int methodB(int value) {
Before Java 8, interfaces could not implement any methods and all methods were implicitly public and abstract.
return value + 100;
<lang java>public interface Inter {
}
int method1(double value);
 
int method2(String name);
int addmethodC(int avalueA, int bvalueB);
}
}</lang>
</syntaxhighlight>
And here is an example of its implementing class.
<syntaxhighlight lang="java">
class ExampleImpl implements Example {
public int methodB(int value) {
return value + 200;
}
 
public int methodC(int valueA, int valueB) {
return valueA + valueB;
}
}
</syntaxhighlight>
The <code>abstract class</code> is very generalized, and for the most part is just a <code>class</code> that allows for un-implemented methods.<br />
The <code>default</code> access modifier is not used here, as it applies only to an <code>interface</code>.<br />
Additionally, if a method is marked <code>abstract</code>, then the <code>private</code> access modifier is not allowed, as the concept does not apply.<br />
Here is an example of an <code>abstract class</code>.<br />
If the class contains <code>abstract</code> methods then the class definition must also have the <code>abstract</code> keyword.
<syntaxhighlight lang="java">
abstract class Example {
String stringA = "rosetta";
String stringB = "code";
 
private String methodA() {
return stringA + " " + stringB;
}
 
protected int methodB(int value) {
return value + 100;
}
 
public abstract int methodC(int valueA, int valueB);
}
</syntaxhighlight>
Here is an example of a class which <code>extends</code> an <code>abstract class</code>.
<syntaxhighlight lang="java">
class ExampleImpl extends Example {
public int methodC(int valueA, int valueB) {
return valueA + valueB;
}
}
</syntaxhighlight>
 
=={{header|jq}}==
jq does not support abstract types but has a namespace-based module system which can be used
to support an "abstract type" approach of programming, as
illustrated here using an extension of the Beast/Cat/Dog example.
 
The following is tailored to the C implementation of jq but could also be adapted for the Go implementation.
<syntaxhighlight lang=jq>
def Beast::new($kind; $name): {
superclass: "Beast",
class: null,
$kind,
$name,
cry: "unspecified"
};
 
def Ape::new($kind; $name):
Beast::new($kind; $name)
| .class = "Ape"
| .cry = "Hoot";
 
def Cat::new($kind; $name):
Beast::new($kind; $name)
| .class = "Cat"
| .cry = "Meow";
 
def Dog::new($kind; $name):
Beast::new($kind; $name)
| .class = "Dog"
| .cry = "Woof";
 
 
def print:
def a($noun):
$noun
| if .[0:1] | test("[aeio]") then "an \(.)" else "a \(.)" end;
 
if .class == null
then "\(.name) is \(a(.kind)), which is an unknown type of \(.superclass)."
else "\(.name) is \(a(.kind)), a type of \(.class), and cries: \(.cry)."
end;
 
Beast::new("sasquatch"; "Bigfoot"),
Ape::new("chimpanzee"; "Nim Chimsky"),
Dog::new("labrador"; "Max"),
Cat::new("siamese"; "Sammy")
| print
</syntaxhighlight>
{{output}}
<pre>
Bigfoot is a sasquatch, which is an unknown type of Beast.
Nim Chimsky is a chimpanzee, a type of Ape, and cries: Hoot.
Max is a labrador, a type of Dog, and cries: Woof.
Sammy is a siamese, a type of Cat, and cries: Meow.
</pre>
 
=={{header|Julia}}==
Line 1,295 ⟶ 1,555:
 
Usage:
<langsyntaxhighlight lang="julia">abstract type «name» end
abstract type «name» <: «supertype» end</langsyntaxhighlight>
 
Examples:
<langsyntaxhighlight lang="julia">abstract type Number end
abstract type Real <: Number end
abstract type FloatingPoint <: Real end
abstract type Integer <: Real end
abstract type Signed <: Integer end
abstract type Unsigned <: Integer end</langsyntaxhighlight>
 
See more [http://docs.julialang.org/en/latest/manual/types/#abstract-types]
Line 1,312 ⟶ 1,572:
 
Here's a very simple (and silly) example of both:
<langsyntaxhighlight lang="scala">// version 1.1
 
interface Announcer {
Line 1,366 ⟶ 1,626:
announceName() // inherits Announcer's implementation
}
}</langsyntaxhighlight>
 
{{out}}
Line 1,381 ⟶ 1,641:
=={{header|Lasso}}==
Instead of abstract classes or interfaces, Lasso uses a [http://lassoguide.com/language/types.html trait system].
<langsyntaxhighlight lang="lasso">define abstract_trait => trait {
require get(index::integer)
Line 1,401 ⟶ 1,661:
#test->second + "\n"
#test->third + "\n"
#test->fourth + "\n"</langsyntaxhighlight>
 
{{out}}
Line 1,416 ⟶ 1,676:
 
In some movie script:
<langsyntaxhighlight lang="lingo">on extendAbstractClass (instance, abstractClass)
-- 'raw' instance of abstract class is made parent ("ancestor") of the
-- passed instance, i.e. the passed instance extends the abstract class
instance.setProp(#ancestor, abstractClass.rawNew())
end</langsyntaxhighlight>
 
Parent script "AbstractClass":
<langsyntaxhighlight lang="lingo">-- instantiation of abstract class by calling its constructor fails
on new (me)
-- optional: show error message as alert
Line 1,434 ⟶ 1,694:
put me.ringtone
end repeat
end</langsyntaxhighlight>
 
Parent script "MyClass"
<langsyntaxhighlight lang="lingo">property ringtone
 
on new (me)
Line 1,447 ⟶ 1,707:
on foo (me)
put "FOO"
end</langsyntaxhighlight>
 
Usage:
<langsyntaxhighlight lang="lingo">obj = script("MyClass").new()
obj.ring(3)
-- "Bell"
Line 1,459 ⟶ 1,719:
test = script("AbstractClass").new()
put test
-- <Void></langsyntaxhighlight>
 
=== Interfaces ===
 
In some movie script:
<langsyntaxhighlight lang="lingo">on implementsInterface (instance, interfaceClass)
interfaceFuncs = interfaceClass.handlers()
funcs = instance.handlers()
Line 1,475 ⟶ 1,735:
end repeat
return TRUE
end</langsyntaxhighlight>
 
Parent script "InterfaceClass":
(Note: in Lingo closing function definitions with "end" is optional, so this a valid definition of 3 empty functions)
<langsyntaxhighlight lang="lingo">on foo
on bar
on foobar</langsyntaxhighlight>
 
Parent script "MyClass":
<langsyntaxhighlight lang="lingo">on new (me)
-- if this class doesn't implement all functions of the
-- interface class, instantiation fails
Line 1,503 ⟶ 1,763:
on foobar (me)
put "FOOBAR"
end</langsyntaxhighlight>
 
Usage:
<langsyntaxhighlight lang="lingo">obj = script("MyClass").new()
put obj -- would show <Void> if interface is not fully implemented
-- <offspring "MyClass" 2 171868></langsyntaxhighlight>
 
=={{header|Logtalk}}==
Line 1,514 ⟶ 1,774:
 
Logtalk supports the definition of interfaces (protocols), which can contain public, protected, and private declarations of methods (predicates). In addition, an object can qualify an implements relation with an interface (protocol) using the keywords "public", "protected", and "private".
<langsyntaxhighlight lang="logtalk">
:- protocol(datep).
 
Line 1,524 ⟶ 1,784:
 
:- end_protocol.
</syntaxhighlight>
</lang>
 
=={{header|Lua}}==
Lua does not include built-in object oriented paradigms. These features can be added using simple code such as the following:
<langsyntaxhighlight lang="lua">BaseClass = {}
 
function class ( baseClass )
Line 1,561 ⟶ 1,821:
 
BaseClass.class = class
BaseClass.abstractClass = abstractClass</langsyntaxhighlight>
The 'class' function produces a new class from an existing parent class (BaseClass is default). From this class other classes or instances can be created. If a class is created through the 'abstractClass' function, however, the resulting class will throw an error if one attempts to instantiate it. Example:
<langsyntaxhighlight lang="lua">A = class() -- New class A inherits BaseClass by default
AA = A:class() -- New class AA inherits from existing class A
B = abstractClass() -- New abstract class B
Line 1,570 ⟶ 1,830:
AA:new() -- Okay: New class instance
B:new() -- Error: B is abstract
BB:new() -- Okay: BB is not abstract</langsyntaxhighlight>
 
=={{header|M2000 Interpreter}}==
M2000 not use interfaces, but can combine groups (used as objects), and because we can alter definitions, we can make an Abstract group by implement modules and functions with a call to Error "not implement yet"
<syntaxhighlight lang="m2000 interpreter">Class BaseState {
Private:
      x as double=1212, z1 as currency=1000, k$="ok"
Line 1,636 ⟶ 1,896:
      \\ we can use For Object {} and a dot before members to get access
      Print .z=1050.12, ExpType$(.z), Type$(.z) ' true, Currency, Group
}</syntaxhighlight>
}
</lang>
 
=={{header|Mathematica}}/{{header|Wolfram Language}}==
 
Mathematica is a symbolic language and as such does not support traditional object oriented design patterns. However, it is quite easy to define pseudo-interfaces that depend on an object implementing a set of functions:
 
<syntaxhighlight lang="mathematica">
<lang Mathematica>
(* Define an interface, Foo, which requires that the functions Foo, Bar, and Baz be defined *)
InterfaceFooQ[obj_] := ValueQ[Foo[obj]] && ValueQ[Bar[obj]] && ValueQ[Baz[obj]];
Line 1,670 ⟶ 1,929:
(* And finally a non-specific string *)
PrintFoo["foobarbaz"]
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 1,690 ⟶ 1,949:
=={{header|MATLAB}}==
; Abstract Class
<langsyntaxhighlight MATLABlang="matlab">classdef (Abstract) AbsClass
...
end</langsyntaxhighlight>
For classes that declare the Abstract class attribute:
* Concrete subclasses must redefine any properties or methods that are declared as abstract.
Line 1,698 ⟶ 1,957:
When you define any abstract methods or properties, MATLAB® automatically sets the class Abstract attribute to true.
; Abstract Methods
<langsyntaxhighlight MATLABlang="matlab">methods (Abstract)
abstMethod(obj)
end</langsyntaxhighlight>
For methods that declare the Abstract method attribute:
* Do not use a function...end block to define an abstract method, use only the method signature.
Line 1,706 ⟶ 1,965:
* Concrete subclasses are not required to support the same number of input and output arguments and do not need to use the same argument names. However, subclasses generally use the same signature when implementing their version of the method.
; Abstract Properties
<langsyntaxhighlight MATLABlang="matlab">properties (Abstract)
AbsProp
end</langsyntaxhighlight>
For properties that declare the Abstract property attribute:
* Concrete subclasses must redefine abstract properties without the Abstract attribute.
Line 1,730 ⟶ 1,989:
these features by default for all tpyes.
 
<langsyntaxhighlight Mercurylang="mercury">:- module eq.
:- interface.
 
Line 1,755 ⟶ 2,014:
A == B :- (A^x = B^x, A^str = B^str),
A \= B :- not A == B
].</langsyntaxhighlight>
 
=={{header|Nemerle}}==
<langsyntaxhighlight Nemerlelang="nemerle">using System.Console;
 
namespace RosettaCode
Line 1,795 ⟶ 2,054:
}
}
}</langsyntaxhighlight>
 
=={{header|NetRexx}}==
<langsyntaxhighlight NetRexxlang="netrexx">/* NetRexx */
options replace format comments java crossref symbols binary
 
Line 1,870 ⟶ 2,129:
method callOverridden2() public returns String
return super.canOverride2
</syntaxhighlight>
</lang>
;Output
<pre>
Line 1,883 ⟶ 2,142:
</pre>
 
=={{header|NewLISPnewLISP}}==
 
<langsyntaxhighlight NewLISPlang="newlisp">; file: abstract.lsp
; url: http://rosettacode.org/wiki/Abstract_type
; author: oofoe 2012-01-28
Line 1,930 ⟶ 2,189:
(:draw (Rectangle "R" 32 4))
 
(exit)</langsyntaxhighlight>
 
Sample output:
Line 1,950 ⟶ 2,209:
=={{header|Nim}}==
In Nim type classes can be seen as an abstract type. Type classes specify interfaces, which can be instantiated by concrete types.
<langsyntaxhighlight lang="nim">type
Comparable = concept x, y
(x < y) is bool
Line 1,961 ⟶ 2,220:
for value in s:
value is T</langsyntaxhighlight>
 
=={{header|Nit}}==
Line 1,967 ⟶ 2,226:
Source: [https://github.com/nitlang/nit/blob/master/examples/rosettacode/abstract_type.nit the official Nit’s repository]
 
<langsyntaxhighlight lang="nit"># Task: abstract type
#
# Methods without implementation are annotated `abstract`.
Line 1,984 ⟶ 2,243:
fun method2: Int do return 1
var attr: Int
end</langsyntaxhighlight>
 
=={{header|Oberon-2}}==
{{Works with|oo2c Version 2}}
<langsyntaxhighlight lang="oberon2">
TYPE
Animal = POINTER TO AnimalDesc;
Line 1,996 ⟶ 2,255:
Cat = POINTER TO CatDesc;
CatDesc = RECORD (AnimalDesc) END;
</syntaxhighlight>
</lang>
 
=={{header|Objeck}}==
<langsyntaxhighlight lang="objeck">
class ClassA {
method : virtual : public : MethodA() ~ Int;
Line 2,007 ⟶ 2,266:
}
}
</syntaxhighlight>
</lang>
 
=={{header|OCaml}}==
Line 2,015 ⟶ 2,274:
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''':
 
<langsyntaxhighlight lang="ocaml">class virtual foo =
object
method virtual bar : int
end</langsyntaxhighlight>
 
===Abstract Type===
 
In OCaml what we call an abstract type is not OO related, it is only a type defined without definition, for example:
<syntaxhighlight lang ="ocaml">type t</langsyntaxhighlight>
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:
<langsyntaxhighlight lang="ocaml">module Foo : sig
type t
end = struct
type t = int * int
end</langsyntaxhighlight>
 
Pure abstract types in the implementation:
<langsyntaxhighlight lang="ocaml">type u
type v
type 'a t
type ut = u t
type vt = v t</langsyntaxhighlight>
 
=={{header|Oforth}}==
Line 2,048 ⟶ 2,307:
Unlike interfaces, properties can include method implementations and attributes (see lang/Comparable.of for instance).
 
<langsyntaxhighlight Oforthlang="oforth">Property new: Spherical(r)
Spherical method: radius @r ;
Spherical method: setRadius := r ;
Line 2,060 ⟶ 2,319:
Object Class new: Planete(name)
Planete is: Spherical
Planete method: initialize(n, r) n := name self setRadius(r) ;</langsyntaxhighlight>
 
Usage :
<langsyntaxhighlight Oforthlang="oforth">: testProperty
| b p |
Ballon new($red, 0.1) ->b
Line 2,074 ⟶ 2,333:
System.Out "Earth perimeter is : " << p perimeter << cr
System.Out "Earth surface is : " << p surface << cr
;</langsyntaxhighlight>
 
{{out}}
Line 2,089 ⟶ 2,348:
 
===Interface===
<langsyntaxhighlight ooRexxlang="oorexx"> -- Example showing a class that defines an interface in ooRexx
-- shape is the interface class that defines the methods a shape instance
-- is expected to implement as abstract methods. Instances of the shape
Line 2,148 ⟶ 2,407:
 
::method name
return "Circle"</langsyntaxhighlight>
{{out}}
<pre>a RECTANGLE
Line 2,164 ⟶ 2,423:
 
===Abstract Type===
<langsyntaxhighlight ooRexxlang="oorexx"> -- Example showing an abstract type in ooRexx
-- shape is the abstract class that defines the abstract method area
-- which is then implemented by its two subclasses, rectangle and circle
Line 2,214 ⟶ 2,473:
expose radius
numeric digits 20
return radius*radius*3.14159265358979323846</langsyntaxhighlight>
{{out}}
<pre>a RECTANGLE
Line 2,233 ⟶ 2,492:
<pre>
 
'ABSTRACT TYPETYPES FOR CONTAINING THINGSEXAMPLE
'PARTICLES
 
type position {}
macro ContainerClass(name,body)
type angle {}
type name##Type body
type velocity {}
class name
type mass {}
'
type counter {}
string buffer
'
method constructor(sys n=1)
buffer=nuls n*sizeof name##Type
end method
'
method destructor()
buffer=""
end method
'
method GetMembers(sys i,n) as name##Type
sys le=len buffer
sys en=(n+i)*sizeof name##type
if le<en
buffer+=nuls en-le 'auto expand
end if
return i+strptr buffer
end method
'
end macro
 
type particle
position p
angle a
velocity v
mass m
end type
 
class particles
'CREATE CLASS
particle*q
 
counter c
ContainerClass Vector3dArray, {double x,y,z}
method constructor (){}
'...
method destructor (){}
method action (){}
end class
 
 
'CREATE OBJECT
 
new Vector3dArray v(100)
 
 
'OBTAIN POINTER AND FILL CHUNK
 
let pv=v.GetMembers(50,3) 'offset, quantity
pv<=1,2,3, 10,20,30, 100,200,300
'...
 
'TEST
 
print pv[3].y
 
del v
 
</pre>
Line 2,292 ⟶ 2,523:
There are no abstract types as part of the language, but we can do as in Python and raise exceptions:
 
<langsyntaxhighlight lang="oz">declare
class BaseQueue
attr
Line 2,314 ⟶ 2,545:
end
 
Queue = {New BaseQueue init} %% throws</langsyntaxhighlight>
 
=={{header|PARI/GP}} ==
GP is not object-oriented and cannot sensibly use abstract types. PARI can use the same solution as [[#C|C]].
 
=={{header|Pascal}} and {{header|Object Pascal}} ==
In ObjectPascal mode FreePascal has classes and abstract methods.
 
Line 2,326 ⟶ 2,557:
=={{header|Perl}}==
 
<langsyntaxhighlight lang="perl">package AbstractFoo;
 
use strict;
Line 2,339 ⟶ 2,570:
 
 
1;</langsyntaxhighlight>
Since Perl 5.12, the Yadda Yadda operator (...) dies with an Unimplemented error,
 
<langsyntaxhighlight lang="perl">
package AbstractFoo;
Line 2,356 ⟶ 2,587:
 
1;
</syntaxhighlight>
</lang>
Raku inspired roles are provided by the [http://search.cpan.org/perldoc?Moose Moose] library
 
<langsyntaxhighlight lang="perl">package AbstractFoo;
 
use Moose::Role;
Line 2,370 ⟶ 2,601:
}
 
1;</langsyntaxhighlight>
Roles are also provided in a more lightweight form with [http://search.cpan.org/perldoc?Role::Tiny Role::Tiny] library
 
<langsyntaxhighlight lang="perl">package AbstractFoo;
 
use Role::Tiny;
Line 2,384 ⟶ 2,615:
}
 
1;</langsyntaxhighlight>
 
=={{header|Phix}}==
Line 2,391 ⟶ 2,622:
 
You can also have explicitly abstract classes (and/or abstract methods). Needs 0.8.1+
<!--<langsyntaxhighlight Phixlang="phix">-->
<span style="color: #008080;">abstract</span> <span style="color: #008080;">class</span> <span style="color: #000000;">job</span>
<span style="color: #004080;">integer</span> <span style="color: #000000;">id</span>
Line 2,405 ⟶ 2,636:
<span style="color: #000000;">errand</span> <span style="color: #000000;">e</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">new</span><span style="color: #0000FF;">({</span><span style="color: #000000;">2</span><span style="color: #0000FF;">})</span>
<span style="color: #000000;">e</span><span style="color: #0000FF;">.</span><span style="color: #000000;">show</span><span style="color: #0000FF;">()</span>
<!--</langsyntaxhighlight>-->
{{out}}
<pre>
Line 2,415 ⟶ 2,646:
 
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
<langsyntaxhighlight lang="php">abstract class Abs {
abstract public function method1($value);
abstract protected function method2($name);
Line 2,421 ⟶ 2,652:
return a + b;
}
}</langsyntaxhighlight>
Interfaces in PHP may not implement any methods and all methods are public and implicitly abstract.
<langsyntaxhighlight lang="php">interface Inter {
public function method1($value);
public function method2($name);
public function add($a, $b);
}</langsyntaxhighlight>
 
=={{header|PicoLisp}}==
<langsyntaxhighlight PicoLisplang="picolisp"># In PicoLisp there is no formal difference between abstract and concrete classes.
# There is just a naming convention where abstract classes start with a
# lower-case character after the '+' (the naming convention for classes).
Line 2,440 ⟶ 2,671:
(dm someMethod> ()
(foo)
(bar) )</langsyntaxhighlight>
 
=={{header|PowerShell}}==
<syntaxhighlight lang="powershell">
<lang PowerShell>
#Requires -Version 5.0
 
Line 2,536 ⟶ 2,767:
}
}
</syntaxhighlight>
</lang>
Create a new player:
<syntaxhighlight lang="powershell">
<lang PowerShell>
$player1 = [Player]::new("sam bradford", "philadelphia eagles", "qb", 7)
$player1
</syntaxhighlight>
</lang>
{{Out}}
<pre>
Line 2,549 ⟶ 2,780:
</pre>
Trade the player:
<syntaxhighlight lang="powershell">
<lang PowerShell>
$player1.Trade("minnesota vikings", 8)
$player1
</syntaxhighlight>
</lang>
{{Out}}
<pre>
Line 2,560 ⟶ 2,791:
</pre>
Create a new player:
<syntaxhighlight lang="powershell">
<lang PowerShell>
$player2 = [Player]::new("demarco murray", "philadelphia eagles", "rb", 29)
$player2
</syntaxhighlight>
</lang>
{{Out}}
<pre>
Line 2,571 ⟶ 2,802:
</pre>
Trade the player:
<syntaxhighlight lang="powershell">
<lang PowerShell>
$player2.Trade("tennessee titans")
$player2
</syntaxhighlight>
</lang>
{{Out}}
<pre>
Line 2,584 ⟶ 2,815:
=={{header|Python}}==
 
<langsyntaxhighlight lang="python">class BaseQueue(object):
"""Abstract/Virtual Class
"""
Line 2,596 ⟶ 2,827:
def Print_Contents(self):
for i in self.contents:
print i,</langsyntaxhighlight>
 
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).
Line 2,609 ⟶ 2,840:
 
Starting from Python 2.6, abstract classes can be created using the standard abc module:
<langsyntaxhighlight lang="python">from abc import ABCMeta, abstractmethod
 
class BaseQueue():
Line 2,629 ⟶ 2,860:
def Print_Contents(self):
for i in self.contents:
print i,</langsyntaxhighlight>
 
=={{header|Racket}}==
 
<langsyntaxhighlight lang="racket">
#lang racket
 
Line 2,647 ⟶ 2,878:
(define tom (new cat%))
(send tom say)
</syntaxhighlight>
</lang>
 
=={{header|Raku}}==
Line 2,655 ⟶ 2,886:
Raku supports roles, which are a bit like interfaces, but unlike interfaces in Java they can also contain some implementation.
 
<syntaxhighlight lang="raku" line>
<lang perl6>
use v6;
 
Line 2,679 ⟶ 2,910:
# made concrete in class
# 42
</syntaxhighlight>
</lang>
 
=={{header|REBOL}}==
<langsyntaxhighlight REBOLlang="rebol">REBOL [
Title: "Abstract Type"
URL: http://rosettacode.org/wiki/Abstract_type
Line 2,725 ⟶ 2,956:
 
print [crlf "A rectangle:"]
r: make rectangle [size: 32x5] r/draw</langsyntaxhighlight>
 
=={{header|Red}}==
<langsyntaxhighlight Redlang="red">Red [
Title: "Abstract Type"
Original-Author: oofoe
Line 2,772 ⟶ 3,003:
 
print [newline "A rectangle:"]
r: make rectangle [size: 32x5] r/draw</langsyntaxhighlight>
 
=={{header|ReScript}}==
Here is an abstract type definition:
<syntaxhighlight lang="rescript">type t</syntaxhighlight>
 
=={{header|REXX}}==
Line 2,783 ⟶ 3,018:
The Python and Tcl provisos apply to Ruby too. Nevertheless, a {{libheader|RubyGems}} package called [http://github.com/Peeja/abstraction/tree/master abstraction] exists where:
 
<langsyntaxhighlight lang="ruby">require 'abstraction'
 
class AbstractQueue
Line 2,799 ⟶ 3,034:
puts "enqueue #{object.inspect}"
end
end</langsyntaxhighlight>
So:
<pre>irb(main):032:0> a = AbstractQueue.new
Line 2,821 ⟶ 3,056:
Rust doesn't have traditional object oriented concepts such as classes, instead it uses a concept called traits. Traits are similar to abstract classes in the sense that they define an interface a struct must conform to. A trait can be defined as such:
 
<langsyntaxhighlight lang="rust">trait Shape {
fn area(self) -> i32;
}</langsyntaxhighlight>
 
The trait can then be implemented on a struct.
 
<langsyntaxhighlight lang="rust">struct Square {
side_length: i32
}
Line 2,835 ⟶ 3,070:
self.side_length * self.side_length
}
}</langsyntaxhighlight>
 
Note, traits can also have a default implementation:
 
<langsyntaxhighlight lang="rust">trait Shape {
fn area(self) -> i32;
 
Line 2,845 ⟶ 3,080:
true
}
}</langsyntaxhighlight>
 
=={{header|Scala}}==
Line 2,861 ⟶ 3,096:
different meaning that described in this page. Here are some examples:
 
<langsyntaxhighlight lang="scala">abstract class X {
type A
var B: A
Line 2,870 ⟶ 3,105:
trait Y {
val x: X
}</langsyntaxhighlight>
 
When integrating with Java, traits without implementation appear as interfaces.
Line 2,883 ⟶ 3,118:
A function is automaticall attached to the interface, when it has an parameter of the interface type.
 
<langsyntaxhighlight lang="seed7">
const type: myInterf is sub object interface;
 
Line 2,889 ⟶ 3,124:
const func integer: method2 (in myInterf: interf, in string: name) is DYNAMIC;
const func integer: add (in myInterf: interf, in integer: a, in integer: b) is DYNAMIC;
</syntaxhighlight>
</lang>
 
=={{header|Sidef}}==
{{trans|Raku}}
<langsyntaxhighlight lang="ruby">class A {
# must be filled in by the class which will inherit it
method abstract() { die 'Unimplemented' };
Line 2,909 ⟶ 3,144:
var obj = SomeClass.new;
obj.abstract(); # made concrete in class
obj.concrete(); # 42</langsyntaxhighlight>
 
=={{header|Simula}}==
Abtract Datatypes are declared using the VIRTUAL keyword.
For example, we need the following two procedures hash and equalto for a hash map implementation.
<langsyntaxhighlight lang="simula">
! ABSTRACT HASH KEY TYPE ;
LISTVAL CLASS HASHKEY;
Line 2,924 ⟶ 3,159:
BEGIN
END HASHKEY;
</syntaxhighlight>
</lang>
A concrete implementation can be derived as follows:
<langsyntaxhighlight lang="simula">
! COMMON HASH KEY TYPE IS TEXT ;
HASHKEY CLASS TEXTHASHKEY(T); VALUE T; TEXT T;
Line 2,947 ⟶ 3,182:
EQUALTO := T = K QUA TEXTHASHKEY.T;
END TEXTHASHKEY;
</syntaxhighlight>
</lang>
=={{header|Skew}}==
{{works with|skewc|0.9.19}}
 
In Skew, interfaces must be explicitly implemented with `::`.
 
<syntaxhighlight lang="skew">
@entry
def main {
var rgb = Rgb.new(0, 255, 255)
var hex = Hex.new("00ffff")
 
var color Color
color = hex
color.print
 
color = rgb
color.print
 
(hex as Color).print
}
 
interface Color {
def toString string
def print {
dynamic.console.log(self.toString)
}
}
 
class Rgb :: Color {
var r int, g int, b int
def toString string { return "rgb(\(r), \(g), \(b))" }
}
 
class Hex :: Color {
var code string
def toString string { return "#\(code)" }
}
</syntaxhighlight>
 
 
=={{header|Smalltalk}}==
A class is declared abtract by responding to the query <tt>isAbstract</tt> with true, and defining the required protocol for subclasses to raise an error notification. Optionally, instance creation can be blocked (but seldom done, as you will hit a subclassResponsibility anyway soon). Typically, the IDE provides menu functions to generate these definitions automatically (eg. "Insert Abstract Class" in the refactoring submenu of the class browser):
<langsyntaxhighlight lang="smalltalk">someClass class >> isAbstract
^ true
 
Line 2,961 ⟶ 3,236:
someClass >> method1
^ self subclassResponsibility
</syntaxhighlight>
</lang>
 
=={{header|Standard ML}}==
Line 2,968 ⟶ 3,243:
 
The act of giving a signature to a module is called ascription. There are two type of ascription:
Transparent (written <tt>:</tt>) and opaque (written <tt>:></tt>). If a structure is ascribed transparently,
none of the types are abstract. If it is ascribed opaquely, all types are abstract by default, but can be specified
explicitly in the signature, in which case they are not abstract.
 
Here is an example signature for a queue data structure:
<langsyntaxhighlight lang="sml">signature QUEUE = sig
type 'a queue
val empty : 'a queue
val enqueue : 'a -> 'a queue -> 'a queue
val dequeue : 'a queue -> ('a * 'a queue) option
end</langsyntaxhighlight>
 
Because we did not specify an implementation for <tt>'a queue</tt>, the type
will be abstract if we use opaque ascription. Instead we could create a version of the signature which specifies the type,
in which case it will never be abstract:
<langsyntaxhighlight lang="sml">signature LIST_QUEUE = sig
type 'a queue = 'a list
val empty : 'a queue
val enqueue : 'a -> 'a queue -> 'a queue
val dequeue : 'a queue -> ('a * 'a queue) option
end</langsyntaxhighlight>
 
Then say we have a structure ListQueue which implements queues as lists. If we write <tt>ListQueue :> QUEUE</tt>
then the queue type will be abstract, but if we write <tt>ListQueue : QUEUE</tt> or <tt>ListQueue : LIST_QUEUE</tt> it won't.
 
=={{header|Swift}}==
Swift uses Protocols to provide abstract type features. See [https://docs.swift.org/swift-book/documentation/the-swift-programming-language/protocols/ the docs]
 
A trivial example showing required properties and methods, and the means of providing a default implementation.
<syntaxhighlight lang="sml">
protocol Pet {
var name: String { get set }
var favouriteToy: String { get set }
 
func feed() -> Bool
 
func stroke() -> Void
 
}
 
extension Pet {
// Default implementation must be in an extension, not in the declaration above
 
func stroke() {
print("default purr")
}
}
 
struct Dog: Pet {
var name: String
var favouriteToy: String
// Required implementation
func feed() -> Bool {
print("more please")
return false
}
// If this were not implemented, the default from the extension above
// would be called.
func stroke() {
print("roll over")
}
}
 
</syntaxhighlight>
 
=={{header|Tcl}}==
Line 2,997 ⟶ 3,313:
 
While in general Tcl does not use abstract classes at all (and has no need at all for interfaces due to supporting multiple inheritance and mixins), an equivalent effect can be had by concealing the construction methods on the class instance; instances are only created by subclassing the class first (or by mixing it in). In this example, the methods are also error-returning stubs...
<langsyntaxhighlight Tcllang="tcl">oo::class create AbstractQueue {
method enqueue item {
error "not implemented"
Line 3,005 ⟶ 3,321:
}
self unexport create new
}</langsyntaxhighlight>
 
{{omit from|TorqueScript}}
 
=={{header|Vala}}==
<langsyntaxhighlight lang="vala">public abstract class Animal : Object {
public void eat() {
print("Chomp! Chomp!\n");
Line 3,038 ⟶ 3,353:
scott.talk();
scott.eat();
}</langsyntaxhighlight>
 
{{out}}
Line 3,065 ⟶ 3,380:
* By convention all abstract classes have one or more Protected constructors.
 
<langsyntaxhighlight lang="vbnet">MustInherit Class Base
 
Protected Sub New()
Line 3,081 ⟶ 3,396:
Public MustOverride Sub Method_Must_Be_Replaced()
 
End Class</langsyntaxhighlight>
 
=== Interfaces ===
Line 3,087 ⟶ 3,402:
Interfaces may contain Functions, Subroutines, Properties, and Events.
 
<langsyntaxhighlight lang="vbnet">Interface IBase
Sub Method_Must_Be_Implemented()
End Interface</langsyntaxhighlight>
 
=={{header|V (Vlang)}}==
{{trans|go}}
V (Vlang) ''interface type'' is an abstract type. It defines a set of methods that a ''concrete type'' must have to satisfy it.
 
A variable of an interface type can hold a value of any type that implements the methods that are specified in the interface. You don't need to explicitly "declare" that the type "implements" the interface or anything like that -- the compatibility is purely structural based on the methods.
 
In the following example, the Dog and Cat types both satisfy the Beast interface because they each have the specified methods. The ''bprint'' function can print details for any Beast.
 
<syntaxhighlight lang="v (vlang)">interface Beast {
kind() string
name() string
cry() string
}
struct Dog {
kind string
name string
}
fn (d Dog) kind() string { return d.kind }
fn (d Dog) name() string { return d.name }
fn (d Dog) cry() string { return "Woof" }
struct Cat {
kind string
name string
}
fn (c Cat) kind() string { return c.kind }
fn (c Cat) name() string { return c.name }
fn (c Cat) cry() string { return "Meow" }
fn bprint(b Beast) {
println("${b.name()}, who's a ${b.kind()}, cries: ${b.cry()}.")
}
fn main() {
d := Dog{"labrador", "Max"}
c := Cat{"siamese", "Sammy"}
bprint(d)
bprint(c)
}</syntaxhighlight>
 
{{out}}
<pre>
Max, who's a labrador, cries: "Woof".
Sammy, who's a siamese, cries: "Meow".
</pre>
 
=={{header|Wren}}==
Line 3,095 ⟶ 3,463:
 
The Go example, when rewritten in Wren, looks like this.
<langsyntaxhighlight ecmascriptlang="wren">import "./fmt" for Fmt
 
class Beast{
Line 3,127 ⟶ 3,495:
var c = Cat.new("siamese", "Sammy")
d.print()
c.print()</langsyntaxhighlight>
 
{{out}}
Line 3,137 ⟶ 3,505:
=={{header|zkl}}==
In zkl, nothing is ever abstract, objects are always runnable. However, it is easy to define "meta" objects, objects that define an interface/api for a "class" of objects. For example, it is desirable for "stream" objects (such as File, List, etc) to share semantics so that code doesn't need to know what the source object really is.
<langsyntaxhighlight lang="zkl">class Stream{ // Mostly virtural base class
var [proxy protected]
isBroken = fcn { _broken.isSet() },
Line 3,157 ⟶ 3,525:
fcn writeln(x) { return(self.topdog); }
fcn walker { return((0).walker(*,wap((self.topdog.read.fpM(""))))); }
}</langsyntaxhighlight>
*The topdog property is the "youngest" child in the inheritance tree (root if you view the tree upside down), it allows a "parent" (or super) to access or pass control to, the actual instance.
*If you wish to "force" method implementation, you can have a meta method throw an NotImplementedError. This is run time thing, not compile time.
 
And now for a "real" object:
<langsyntaxhighlight lang="zkl">class DevNull(Stream){
var [const] fileName = "DevNull"; // compatibility with File
fcn init { Stream.init() }
fcn write(x) { return(0); }
}</langsyntaxhighlight>
 
 
{{omit from|ApplesoftAArch64 BASICAssembly}}
{{omit from|ALGOL 68}}
{{omit from|Applesoft BASIC}}
{{omit from|ARM Assembly}}
{{omit from|AWK}}
{{omit from|BASIC}}
Line 3,178 ⟶ 3,548:
{{omit from|Falcon|Does not support the concept of an abstract type.}}
{{omit from|gnuplot}}
{{omit from|Icon}}
{{omit from|Integer BASIC}}
{{omit from|J}}
{{omit from|JavaScript}}
{{omit from|IconJ}}
{{omit from|LaTeX}}
{{omit from|M4}}
{{omit from|Make}}
{{omit from|Mathematica}}
{{omit from|Maxima}}
{{omit from|M4}}
{{omit from|Metafont}}
{{omit from|MiniZinc|no ability to declare new types at all}}
{{omit from|ML/I}}
{{omit from|Modula-2}}
Line 3,196 ⟶ 3,566:
{{omit from|Scratch}}
{{omit from|TI-89 BASIC|Does not have static or user-defined types.}}
{{omit from|TorqueScript}}
{{omit from|UNIX Shell}}
{{omit from|ZX Spectrum Basic}}
Anonymous user