Abstract type: Difference between revisions

m (syntax highlighting fixup automation)
imported>Regattaguru
(16 intermediate revisions by 8 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
 
Line 26 ⟶ 25:
 
=={{header|AArch64 Assembly}}==
{{omit from|AArch64 Assembly}}
 
=={{header|ABAP}}==
=== Abstract Class ===
<syntaxhighlight lang=ABAP"abap">class abs definition abstract.
public section.
methods method1 abstract importing iv_value type f exporting ev_ret type i.
Line 49 ⟶ 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.
<syntaxhighlight lang=ABAP"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,
Line 57 ⟶ 55:
=={{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.
<syntaxhighlight lang="actionscript">package
{
public interface IInterface
Line 67 ⟶ 65:
 
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"actionscript">
package {
import flash.utils.getQualifiedClassName;
Line 93 ⟶ 91:
 
Inheriting this class:
<syntaxhighlight lang=ActionScript"actionscript">
package {
 
Line 109 ⟶ 107:
===Interface===
Interfaces in [[Ada]] may have no components or implemented operation except for ones implemented as null operations. Interfaces can be multiply inherited.
<syntaxhighlight 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;</syntaxhighlight>
Interfaces can be declared synchronized or task when intended implementations are to be provided by protected objects or [[task]]s. For example:
<syntaxhighlight lang="ada">type Scheduler is task interface;
procedure Plan (Manager : in out Scheduler; Activity : in out Job) is abstract;</syntaxhighlight>
===Abstract type===
Abstract types may provide components and implementation of their operations. Abstract types are singly inherited.
<syntaxhighlight lang="ada">with Ada.Finalization;
...
type Node is abstract new Ada.Finalization.Limited_Controlled and Queue with record
Line 132 ⟶ 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:
 
<syntaxhighlight lang="agda">module AbstractInterfaceExample where
 
open import Function
Line 191 ⟶ 189:
An abstract class contains functions that have no body defined. You cannot instantiate a class that contains abstract functions.
 
<syntaxhighlight lang="aikido">class Abs {
public function method1...
public function method2...
Line 197 ⟶ 195:
}</syntaxhighlight>
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.
<syntaxhighlight lang="aikido">interface Inter {
function isFatal : integer
function operate (para : integer = 0)
Line 206 ⟶ 204:
In AmigaE, abstract methods are supported but interfaces are not.
 
<syntaxhighlight lang="amigae">
OBJECT fruit
ENDOBJECT
Line 232 ⟶ 230:
 
=={{header|Apex}}==
<syntaxhighlight lang="apex">
// Interface
public interface PurchaseOrder {
Line 260 ⟶ 258:
=={{header|Argile}}==
{{works with|Argile|1.0.0}}
<syntaxhighlight lang=Argile"argile">use std
 
(: abstract class :)
Line 300 ⟶ 298:
 
 
{{omit from|ARM Assembly}}
 
=={{header|AutoHotkey}}==
{{works with | AutoHotkey_L}}
<syntaxhighlight lang=AutoHotkey"autohotkey">color(r, g, b){
static color
If !color
Line 338 ⟶ 335:
{{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:
<syntaxhighlight lang="bbcbasic"> INSTALL @lib$+"CLASSLIB"
REM Declare a class with no implementation:
Line 359 ⟶ 356:
==={{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"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.
 
Line 423 ⟶ 420:
{{works with|QuickBasic|4.5}}
{{trans|QB64}}
<syntaxhighlight lang="qbasic">a = 15
TYPE c
Line 455 ⟶ 452:
 
The header file for the abstract class, interfaceAbs.h
<syntaxhighlight lang="c">#ifndef INTERFACE_ABS
#define INTERFACE_ABS
 
Line 491 ⟶ 488:
the code is in file silly.h. Note the actual structure of the class is not provided
here. We don't want it visible.
<syntaxhighlight lang="c">#ifndef SILLY_H
#define SILLY_H
#include "intefaceAbs.h"
Line 503 ⟶ 500:
Ok. Now it is necessary to provide the implementation of the realizable class.
This code should be in silly.c.
<syntaxhighlight lang="c">#include "silly.h"
#include <string.h>
#include <stdio.h>
Line 550 ⟶ 547:
 
Now all's left is some example code that uses all this stuff.
<syntaxhighlight lang="c">#include <stdio.h>
#include "silly.h"
 
Line 566 ⟶ 563:
 
=={{header|C sharp|C#}}==
<syntaxhighlight lang="csharp">abstract class Class1
{
public abstract void method1();
Line 578 ⟶ 575:
=={{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.
<syntaxhighlight lang="cpp">class Abs {
public:
virtual int method1(double value) = 0;
Line 591 ⟶ 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.
 
<syntaxhighlight lang="cos">Class Abstract.Class.Shape [ Abstract ]
{
Parameter SHAPE = 1;
Line 609 ⟶ 606:
Data type classes differ because they cannot contain properties, see example below.
 
<syntaxhighlight lang="cos">Class Abstract.DataType.Shape [ ClassType = datatype ]
{
Parameter SHAPE = 1;
Line 641 ⟶ 638:
Using defprotocol, we can define what is essentially an interface.
 
<syntaxhighlight lang="lisp">(defprotocol Foo (foo [this]))</syntaxhighlight>
 
=={{header|COBOL}}==
===Interface===
{{trans|F#}}
<syntaxhighlight lang="cobol"> INTERFACE-ID.IDENTIFICATION ShapeDIVISION.
INTERFACE-ID. Shape.
PROCEDURE DIVISION.
IDENTIFICATION DIVISION.
METHOD-ID. perimeter.
DATA DIVISION.
Line 657 ⟶ 656:
END METHOD perimeter.
IDENTIFICATION DIVISION.
METHOD-ID. shape-area.
DATA DIVISION.
Line 667:
 
IDENTIFICATION DIVISION.
CLASS-ID. Rectangle.
Line 674 ⟶ 675:
INTERFACE Shape.
IDENTIFICATION DIVISION.
OBJECT IMPLEMENTS Shape.
DATA DIVISION.
Line 682 ⟶ 684:
PROCEDURE DIVISION.
IDENTIFICATION DIVISION.
METHOD-ID. perimeter.
DATA DIVISION.
Line 687 ⟶ 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 697 ⟶ 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.
Line 709 ⟶ 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.
 
<syntaxhighlight lang="lisp">(defgeneric kar (kons)
(:documentation "Return the kar of a kons."))
 
Line 725 ⟶ 732:
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.
 
<syntaxhighlight lang="lisp">(defmethod kar ((cons cons))
(car cons))
 
Line 738 ⟶ 745:
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>.
 
<syntaxhighlight lang="lisp">(defmethod kar ((n integer))
1)
 
Line 751 ⟶ 758:
 
=={{header|Component Pascal}}==
<syntaxhighlight lang="oberon2">
(* Abstract type *)
Object = POINTER TO ABSTRACT RECORD END;
Line 765 ⟶ 772:
</syntaxhighlight>
...
<syntaxhighlight lang="oberon2">
(* Abstract method of Object *)
PROCEDURE (dn: Object) Show*, NEW, ABSTRACT;
Line 786 ⟶ 793:
 
=={{header|Crystal}}==
<syntaxhighlight lang="ruby">abstract class Animal # only abstract class can have abstract methods
abstract def move
abstract def think
Line 829 ⟶ 836:
 
=={{header|D}}==
<syntaxhighlight lang="d">import std.stdio;
 
class Foo {
Line 860 ⟶ 867:
Abstract Class introduced in Delphi 2006. An abstract class cannot be instantiated and must be derived from in order to be used.
 
<syntaxhighlight lang="delphi">TSomeClass = class abstract (TObject)
...
end;</syntaxhighlight>
Line 867 ⟶ 874:
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.
 
<syntaxhighlight lang="delphi">type
TMyObject = class(TObject)
public
Line 893 ⟶ 900:
A simple abstract type without enforcement can be created using the interface expression:
 
<syntaxhighlight lang="e">interface Foo {
to bar(a :int, b :int)
}</syntaxhighlight>
Line 899 ⟶ 906:
With enforcement, a separate ''stamp'' is created which must be applied to the instances. This is analogous to a Java interface.
 
<syntaxhighlight lang="e">interface Foo guards FooStamp {
to bar(a :int, b :int)
}
Line 911 ⟶ 918:
=={{header|Eiffel}}==
 
<syntaxhighlight lang=Eiffel"eiffel">
deferred class
AN_ABSTRACT_CLASS
Line 932 ⟶ 939:
 
A more expressive view of an Abstract type in Eiffel:
<syntaxhighlight lang="eiffel">
note
title: "Prototype Person"
Line 997 ⟶ 1,004:
=={{header|Elena}}==
 
<syntaxhighlight lang="elena">abstract class Bike
{
abstract run();
}
</syntaxhighlight>
 
=={{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:
<syntaxhighlight lang="fsharp">type Shape =
abstract Perimeter: unit -> float
abstract Area: unit -> float
Line 1,015 ⟶ 1,069:
 
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:
<syntaxhighlight lang=" fsharp">[<AbstractClass>]
type Bird() =
// an abstract (=virtual) method with default impl.
Line 1,033 ⟶ 1,087:
 
=={{header|Fantom}}==
<syntaxhighlight lang="fantom">
abstract class X
{
Line 1,068 ⟶ 1,122:
{{trans|Fantom}}
There are numerous, mutually incompatible object oriented frameworks for Forth. This one works with the FOOS preprocessor extension of [[4tH]].
<syntaxhighlight lang="forth">include 4pp/lib/foos.4pp
 
:: X()
Line 1,098 ⟶ 1,152:
Needs the FMS-SI (single inheritance) library code located here:
http://soton.mpeforth.com/flag/fms/index.html
<syntaxhighlight lang="forth">include FMS-SI.f
 
The FMS object extension uses duck typing and so has no need for abstract types.
Line 1,105 ⟶ 1,159:
=={{header|Fortran}}==
Simple abstract derived type (i.e. abstract class) in Fortran 2008
<syntaxhighlight lang="fortran">
! abstract derived type
type, abstract :: TFigure
Line 1,129 ⟶ 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 :-
<syntaxhighlight lang="freebasic">' FB 1.05.0 Win64
 
Type Animal Extends Object
Line 1,181 ⟶ 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.
<syntaxhighlight lang="genyris">class AbstractStack()
def .valid?(object) nil
 
Line 1,187 ⟶ 1,241:
 
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'':
<syntaxhighlight lang="genyris">class StackInterface()
def .valid?(object)
object
Line 1,197 ⟶ 1,251:
 
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:
<syntaxhighlight lang="genyris">class XYZstack(Object)
def .init()
var .items ()
Line 1,207 ⟶ 1,261:
tmp</syntaxhighlight>
Now we can tag an object that conforms to the Interface:
<syntaxhighlight lang="genyris">tag StackInterface (XYZstack(.new))</syntaxhighlight>
 
=={{header|Go}}==
Line 1,216 ⟶ 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.
 
<syntaxhighlight lang="go">package main
 
import "fmt"
Line 1,269 ⟶ 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).
<syntaxhighlight lang="groovy">public interface Interface {
int method1(double value)
int method2(String name)
Line 1,276 ⟶ 1,330:
 
An abstract class may implement some of its methods and leave others unimplemented. The unimplemented methods and the class itself must be declared "abstract".
<syntaxhighlight lang="groovy">public abstract class Abstract1 {
abstract public int methodA(Date value)
abstract protected int methodB(String name)
Line 1,283 ⟶ 1,337:
 
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.
<syntaxhighlight lang="groovy">public abstract class Abstract2 implements Interface {
int add(int a, int b) { a + b }
}</syntaxhighlight>
 
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.
<syntaxhighlight 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,307 ⟶ 1,361:
 
Obligatory test:
<syntaxhighlight lang="groovy">def c1 = new Concrete1()
assert c1 instanceof Interface
println (new Concrete1().method2("Superman"))
Line 1,332 ⟶ 1,386:
 
For example, the built-in type class Eq (the types that can be compared for equality) can be declared as follows:
<syntaxhighlight lang="haskell">class Eq a where
(==) :: a -> a -> Bool
(/=) :: a -> a -> Bool</syntaxhighlight>
 
Default implementations of the functions can be provided:
<syntaxhighlight lang="haskell">class Eq a where
(==) :: a -> a -> Bool
(/=) :: a -> a -> Bool
Line 1,345 ⟶ 1,399:
 
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:
<syntaxhighlight lang="haskell">func :: (Eq a) => a -> Bool
func x = x == x</syntaxhighlight>
 
Suppose I make a new type
<syntaxhighlight lang="haskell">data Foo = Foo {x :: Integer, str :: String}</syntaxhighlight>
 
One could then provide an implementation ("instance") the type class Eq with this type
<syntaxhighlight lang="haskell">instance Eq Foo where
(Foo x1 str1) == (Foo x2 str2) =
(x1 == x2) && (str1 == str2)</syntaxhighlight>
Line 1,362 ⟶ 1,416:
An abstract class is a class with abstract methods. Icon is not object-oriented.
 
<syntaxhighlight lang="unicon">class abstraction()
abstract method compare(l,r) # generates runerr(700, "method compare()")
end</syntaxhighlight>
Line 1,378 ⟶ 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() {
<syntaxhighlight 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;
}
 
}</syntaxhighlight>
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;
<syntaxhighlight lang=java>public interface Inter {
}
int method1(double value);
 
int method2(String name);
int addmethodC(int avalueA, int bvalueB);
}
}</syntaxhighlight>
</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,398 ⟶ 1,555:
 
Usage:
<syntaxhighlight lang="julia">abstract type «name» end
abstract type «name» <: «supertype» end</syntaxhighlight>
 
Examples:
<syntaxhighlight lang="julia">abstract type Number end
abstract type Real <: Number end
abstract type FloatingPoint <: Real end
Line 1,415 ⟶ 1,572:
 
Here's a very simple (and silly) example of both:
<syntaxhighlight lang="scala">// version 1.1
 
interface Announcer {
Line 1,484 ⟶ 1,641:
=={{header|Lasso}}==
Instead of abstract classes or interfaces, Lasso uses a [http://lassoguide.com/language/types.html trait system].
<syntaxhighlight lang="lasso">define abstract_trait => trait {
require get(index::integer)
Line 1,519 ⟶ 1,676:
 
In some movie script:
<syntaxhighlight 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
Line 1,526 ⟶ 1,683:
 
Parent script "AbstractClass":
<syntaxhighlight lang="lingo">-- instantiation of abstract class by calling its constructor fails
on new (me)
-- optional: show error message as alert
Line 1,540 ⟶ 1,697:
 
Parent script "MyClass"
<syntaxhighlight lang="lingo">property ringtone
 
on new (me)
Line 1,553 ⟶ 1,710:
 
Usage:
<syntaxhighlight lang="lingo">obj = script("MyClass").new()
obj.ring(3)
-- "Bell"
Line 1,567 ⟶ 1,724:
 
In some movie script:
<syntaxhighlight lang="lingo">on implementsInterface (instance, interfaceClass)
interfaceFuncs = interfaceClass.handlers()
funcs = instance.handlers()
Line 1,582 ⟶ 1,739:
Parent script "InterfaceClass":
(Note: in Lingo closing function definitions with "end" is optional, so this a valid definition of 3 empty functions)
<syntaxhighlight lang="lingo">on foo
on bar
on foobar</syntaxhighlight>
 
Parent script "MyClass":
<syntaxhighlight lang="lingo">on new (me)
-- if this class doesn't implement all functions of the
-- interface class, instantiation fails
Line 1,609 ⟶ 1,766:
 
Usage:
<syntaxhighlight lang="lingo">obj = script("MyClass").new()
put obj -- would show <Void> if interface is not fully implemented
-- <offspring "MyClass" 2 171868></syntaxhighlight>
Line 1,617 ⟶ 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".
<syntaxhighlight lang="logtalk">
:- protocol(datep).
 
Line 1,631 ⟶ 1,788:
=={{header|Lua}}==
Lua does not include built-in object oriented paradigms. These features can be added using simple code such as the following:
<syntaxhighlight lang="lua">BaseClass = {}
 
function class ( baseClass )
Line 1,666 ⟶ 1,823:
BaseClass.abstractClass = abstractClass</syntaxhighlight>
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:
<syntaxhighlight 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,677 ⟶ 1,834:
=={{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"m2000 Interpreterinterpreter">Class BaseState {
Private:
      x as double=1212, z1 as currency=1000, k$="ok"
Line 1,745 ⟶ 1,902:
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"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,792 ⟶ 1,949:
=={{header|MATLAB}}==
; Abstract Class
<syntaxhighlight lang=MATLAB"matlab">classdef (Abstract) AbsClass
...
end</syntaxhighlight>
Line 1,800 ⟶ 1,957:
When you define any abstract methods or properties, MATLAB® automatically sets the class Abstract attribute to true.
; Abstract Methods
<syntaxhighlight lang=MATLAB"matlab">methods (Abstract)
abstMethod(obj)
end</syntaxhighlight>
Line 1,808 ⟶ 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
<syntaxhighlight lang=MATLAB"matlab">properties (Abstract)
AbsProp
end</syntaxhighlight>
Line 1,832 ⟶ 1,989:
these features by default for all tpyes.
 
<syntaxhighlight lang=Mercury"mercury">:- module eq.
:- interface.
 
Line 1,860 ⟶ 2,017:
 
=={{header|Nemerle}}==
<syntaxhighlight lang=Nemerle"nemerle">using System.Console;
 
namespace RosettaCode
Line 1,900 ⟶ 2,057:
 
=={{header|NetRexx}}==
<syntaxhighlight lang=NetRexx"netrexx">/* NetRexx */
options replace format comments java crossref symbols binary
 
Line 1,987 ⟶ 2,144:
=={{header|newLISP}}==
 
<syntaxhighlight lang=newLISP"newlisp">; file: abstract.lsp
; url: http://rosettacode.org/wiki/Abstract_type
; author: oofoe 2012-01-28
Line 2,052 ⟶ 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.
<syntaxhighlight lang="nim">type
Comparable = concept x, y
(x < y) is bool
Line 2,069 ⟶ 2,226:
Source: [https://github.com/nitlang/nit/blob/master/examples/rosettacode/abstract_type.nit the official Nit’s repository]
 
<syntaxhighlight lang="nit"># Task: abstract type
#
# Methods without implementation are annotated `abstract`.
Line 2,090 ⟶ 2,247:
=={{header|Oberon-2}}==
{{Works with|oo2c Version 2}}
<syntaxhighlight lang="oberon2">
TYPE
Animal = POINTER TO AnimalDesc;
Line 2,101 ⟶ 2,258:
 
=={{header|Objeck}}==
<syntaxhighlight lang="objeck">
class ClassA {
method : virtual : public : MethodA() ~ Int;
Line 2,117 ⟶ 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''':
 
<syntaxhighlight lang="ocaml">class virtual foo =
object
method virtual bar : int
Line 2,125 ⟶ 2,282:
 
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</syntaxhighlight>
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:
<syntaxhighlight lang="ocaml">module Foo : sig
type t
end = struct
Line 2,136 ⟶ 2,293:
 
Pure abstract types in the implementation:
<syntaxhighlight lang="ocaml">type u
type v
type 'a t
Line 2,150 ⟶ 2,307:
Unlike interfaces, properties can include method implementations and attributes (see lang/Comparable.of for instance).
 
<syntaxhighlight lang=Oforth"oforth">Property new: Spherical(r)
Spherical method: radius @r ;
Spherical method: setRadius := r ;
Line 2,165 ⟶ 2,322:
 
Usage :
<syntaxhighlight lang=Oforth"oforth">: testProperty
| b p |
Ballon new($red, 0.1) ->b
Line 2,191 ⟶ 2,348:
 
===Interface===
<syntaxhighlight lang=ooRexx"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,266 ⟶ 2,423:
 
===Abstract Type===
<syntaxhighlight lang=ooRexx"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,366 ⟶ 2,523:
There are no abstract types as part of the language, but we can do as in Python and raise exceptions:
 
<syntaxhighlight lang="oz">declare
class BaseQueue
attr
Line 2,400 ⟶ 2,557:
=={{header|Perl}}==
 
<syntaxhighlight lang="perl">package AbstractFoo;
 
use strict;
Line 2,416 ⟶ 2,573:
Since Perl 5.12, the Yadda Yadda operator (...) dies with an Unimplemented error,
 
<syntaxhighlight lang="perl">
package AbstractFoo;
Line 2,433 ⟶ 2,590:
Raku inspired roles are provided by the [http://search.cpan.org/perldoc?Moose Moose] library
 
<syntaxhighlight lang="perl">package AbstractFoo;
 
use Moose::Role;
Line 2,447 ⟶ 2,604:
Roles are also provided in a more lightweight form with [http://search.cpan.org/perldoc?Role::Tiny Role::Tiny] library
 
<syntaxhighlight lang="perl">package AbstractFoo;
 
use Role::Tiny;
Line 2,465 ⟶ 2,622:
 
You can also have explicitly abstract classes (and/or abstract methods). Needs 0.8.1+
<!--<syntaxhighlight lang=Phix"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,489 ⟶ 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
<syntaxhighlight lang="php">abstract class Abs {
abstract public function method1($value);
abstract protected function method2($name);
Line 2,497 ⟶ 2,654:
}</syntaxhighlight>
Interfaces in PHP may not implement any methods and all methods are public and implicitly abstract.
<syntaxhighlight lang="php">interface Inter {
public function method1($value);
public function method2($name);
Line 2,504 ⟶ 2,661:
 
=={{header|PicoLisp}}==
<syntaxhighlight lang=PicoLisp"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,517 ⟶ 2,674:
 
=={{header|PowerShell}}==
<syntaxhighlight lang=PowerShell"powershell">
#Requires -Version 5.0
 
Line 2,612 ⟶ 2,769:
</syntaxhighlight>
Create a new player:
<syntaxhighlight lang=PowerShell"powershell">
$player1 = [Player]::new("sam bradford", "philadelphia eagles", "qb", 7)
$player1
Line 2,623 ⟶ 2,780:
</pre>
Trade the player:
<syntaxhighlight lang=PowerShell"powershell">
$player1.Trade("minnesota vikings", 8)
$player1
Line 2,634 ⟶ 2,791:
</pre>
Create a new player:
<syntaxhighlight lang=PowerShell"powershell">
$player2 = [Player]::new("demarco murray", "philadelphia eagles", "rb", 29)
$player2
Line 2,645 ⟶ 2,802:
</pre>
Trade the player:
<syntaxhighlight lang=PowerShell"powershell">
$player2.Trade("tennessee titans")
$player2
Line 2,658 ⟶ 2,815:
=={{header|Python}}==
 
<syntaxhighlight lang="python">class BaseQueue(object):
"""Abstract/Virtual Class
"""
Line 2,683 ⟶ 2,840:
 
Starting from Python 2.6, abstract classes can be created using the standard abc module:
<syntaxhighlight lang="python">from abc import ABCMeta, abstractmethod
 
class BaseQueue():
Line 2,707 ⟶ 2,864:
=={{header|Racket}}==
 
<syntaxhighlight lang="racket">
#lang racket
 
Line 2,729 ⟶ 2,886:
Raku supports roles, which are a bit like interfaces, but unlike interfaces in Java they can also contain some implementation.
 
<syntaxhighlight lang=perl6"raku" line>
use v6;
 
Line 2,756 ⟶ 2,913:
 
=={{header|REBOL}}==
<syntaxhighlight lang=REBOL"rebol">REBOL [
Title: "Abstract Type"
URL: http://rosettacode.org/wiki/Abstract_type
Line 2,802 ⟶ 2,959:
 
=={{header|Red}}==
<syntaxhighlight lang=Red"red">Red [
Title: "Abstract Type"
Original-Author: oofoe
Line 2,850 ⟶ 3,007:
=={{header|ReScript}}==
Here is an abstract type definition:
<syntaxhighlight lang=ReScript"rescript">type t</syntaxhighlight>
 
=={{header|REXX}}==
Line 2,861 ⟶ 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:
 
<syntaxhighlight lang="ruby">require 'abstraction'
 
class AbstractQueue
Line 2,899 ⟶ 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:
 
<syntaxhighlight lang="rust">trait Shape {
fn area(self) -> i32;
}</syntaxhighlight>
Line 2,905 ⟶ 3,062:
The trait can then be implemented on a struct.
 
<syntaxhighlight lang="rust">struct Square {
side_length: i32
}
Line 2,917 ⟶ 3,074:
Note, traits can also have a default implementation:
 
<syntaxhighlight lang="rust">trait Shape {
fn area(self) -> i32;
 
Line 2,939 ⟶ 3,096:
different meaning that described in this page. Here are some examples:
 
<syntaxhighlight lang="scala">abstract class X {
type A
var B: A
Line 2,961 ⟶ 3,118:
A function is automaticall attached to the interface, when it has an parameter of the interface type.
 
<syntaxhighlight lang="seed7">
const type: myInterf is sub object interface;
 
Line 2,971 ⟶ 3,128:
=={{header|Sidef}}==
{{trans|Raku}}
<syntaxhighlight lang="ruby">class A {
# must be filled in by the class which will inherit it
method abstract() { die 'Unimplemented' };
Line 2,992 ⟶ 3,149:
Abtract Datatypes are declared using the VIRTUAL keyword.
For example, we need the following two procedures hash and equalto for a hash map implementation.
<syntaxhighlight lang="simula">
! ABSTRACT HASH KEY TYPE ;
LISTVAL CLASS HASHKEY;
Line 3,004 ⟶ 3,161:
</syntaxhighlight>
A concrete implementation can be derived as follows:
<syntaxhighlight lang="simula">
! COMMON HASH KEY TYPE IS TEXT ;
HASHKEY CLASS TEXTHASHKEY(T); VALUE T; TEXT T;
Line 3,026 ⟶ 3,183:
END TEXTHASHKEY;
</syntaxhighlight>
=={{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):
<syntaxhighlight lang="smalltalk">someClass class >> isAbstract
^ true
 
Line 3,046 ⟶ 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:
<syntaxhighlight lang="sml">signature QUEUE = sig
type 'a queue
val empty : 'a queue
Line 3,061 ⟶ 3,258:
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:
<syntaxhighlight lang="sml">signature LIST_QUEUE = sig
type 'a queue = 'a list
val empty : 'a queue
Line 3,070 ⟶ 3,267:
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 3,075 ⟶ 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...
<syntaxhighlight lang=Tcl"tcl">oo::class create AbstractQueue {
method enqueue item {
error "not implemented"
Line 3,085 ⟶ 3,323:
}</syntaxhighlight>
 
{{omit from|TorqueScript}}
 
=={{header|Vala}}==
<syntaxhighlight lang="vala">public abstract class Animal : Object {
public void eat() {
print("Chomp! Chomp!\n");
Line 3,143 ⟶ 3,380:
* By convention all abstract classes have one or more Protected constructors.
 
<syntaxhighlight lang="vbnet">MustInherit Class Base
 
Protected Sub New()
Line 3,165 ⟶ 3,402:
Interfaces may contain Functions, Subroutines, Properties, and Events.
 
<syntaxhighlight lang="vbnet">Interface IBase
Sub Method_Must_Be_Implemented()
End Interface</syntaxhighlight>
 
=={{header|V (Vlang)}}==
{{trans|go}}
VlangsV (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.
Line 3,177 ⟶ 3,414:
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
Line 3,226 ⟶ 3,463:
 
The Go example, when rewritten in Wren, looks like this.
<syntaxhighlight lang=ecmascript"wren">import "./fmt" for Fmt
 
class Beast{
Line 3,268 ⟶ 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.
<syntaxhighlight lang="zkl">class Stream{ // Mostly virtural base class
var [proxy protected]
isBroken = fcn { _broken.isSet() },
Line 3,293 ⟶ 3,530:
 
And now for a "real" object:
<syntaxhighlight lang="zkl">class DevNull(Stream){
var [const] fileName = "DevNull"; // compatibility with File
fcn init { Stream.init() }
Line 3,300 ⟶ 3,537:
 
 
{{omit from|ApplesoftAArch64 BASICAssembly}}
{{omit from|ALGOL 68}}
{{omit from|Applesoft BASIC}}
{{omit from|ARM Assembly}}
{{omit from|AWK}}
{{omit from|BASIC}}
Line 3,309 ⟶ 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|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,326 ⟶ 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