Abstract type: Difference between revisions

Content added Content deleted
m (syntax highlighting fixup automation)
m (Automated syntax highlighting fixup (second round - minor fixes))
Line 14: 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.
'''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}}==
=={{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.
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
<syntaxhighlight lang="11l">T AbstractQueue
F.virtual.abstract enqueue(Int item) -> N
F.virtual.abstract enqueue(Int item) -> N


Line 26: Line 25:


=={{header|AArch64 Assembly}}==
=={{header|AArch64 Assembly}}==
{{omit from|AArch64 Assembly}}


=={{header|ABAP}}==
=={{header|ABAP}}==
=== Abstract Class ===
=== Abstract Class ===
<syntaxhighlight lang=ABAP>class abs definition abstract.
<syntaxhighlight lang="abap">class abs definition abstract.
public section.
public section.
methods method1 abstract importing iv_value type f exporting ev_ret type i.
methods method1 abstract importing iv_value type f exporting ev_ret type i.
Line 49: Line 47:
2. Variables must be static final. The values may be computed at run time.
2. Variables must be static final. The values may be computed at run time.
3. No static initialiser blockers. No static initialiser helper methods.
3. No static initialiser blockers. No static initialiser helper methods.
<syntaxhighlight lang=ABAP>interface inter.
<syntaxhighlight lang="abap">interface inter.
methods: method1 importing iv_value type f exporting ev_ret type i,
methods: method1 importing iv_value type f exporting ev_ret type i,
method2 importing iv_name type string exporting ev_ret type i,
method2 importing iv_name type string exporting ev_ret type i,
Line 57: Line 55:
=={{header|ActionScript}}==
=={{header|ActionScript}}==
While ActionScript does not support explicit abstract classes, it does have interfaces. Interfaces in ActionScript may not implement any methods and all methods are public and implicitly abstract. Interfaces can extend other interfaces, and interfaces may be multiply inherited.
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
<syntaxhighlight lang="actionscript">package
{
{
public interface IInterface
public interface IInterface
Line 67: Line 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.
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>
<syntaxhighlight lang="actionscript">
package {
package {
import flash.utils.getQualifiedClassName;
import flash.utils.getQualifiedClassName;
Line 93: Line 91:


Inheriting this class:
Inheriting this class:
<syntaxhighlight lang=ActionScript>
<syntaxhighlight lang="actionscript">
package {
package {


Line 109: Line 107:
===Interface===
===Interface===
Interfaces in [[Ada]] may have no components or implemented operation except for ones implemented as null operations. Interfaces can be multiply inherited.
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;
<syntaxhighlight lang="ada">type Queue is limited interface;
procedure Enqueue (Lounge : in out Queue; Item : in out Element) is abstract;
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>
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:
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;
<syntaxhighlight lang="ada">type Scheduler is task interface;
procedure Plan (Manager : in out Scheduler; Activity : in out Job) is abstract;</syntaxhighlight>
procedure Plan (Manager : in out Scheduler; Activity : in out Job) is abstract;</syntaxhighlight>
===Abstract type===
===Abstract type===
Abstract types may provide components and implementation of their operations. Abstract types are singly inherited.
Abstract types may provide components and implementation of their operations. Abstract types are singly inherited.
<syntaxhighlight lang=ada>with Ada.Finalization;
<syntaxhighlight lang="ada">with Ada.Finalization;
...
...
type Node is abstract new Ada.Finalization.Limited_Controlled and Queue with record
type Node is abstract new Ada.Finalization.Limited_Controlled and Queue with record
Line 132: Line 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:
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
<syntaxhighlight lang="agda">module AbstractInterfaceExample where


open import Function
open import Function
Line 191: Line 189:
An abstract class contains functions that have no body defined. You cannot instantiate a class that contains abstract functions.
An abstract class contains functions that have no body defined. You cannot instantiate a class that contains abstract functions.


<syntaxhighlight lang=aikido>class Abs {
<syntaxhighlight lang="aikido">class Abs {
public function method1...
public function method1...
public function method2...
public function method2...
Line 197: Line 195:
}</syntaxhighlight>
}</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.
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 {
<syntaxhighlight lang="aikido">interface Inter {
function isFatal : integer
function isFatal : integer
function operate (para : integer = 0)
function operate (para : integer = 0)
Line 206: Line 204:
In AmigaE, abstract methods are supported but interfaces are not.
In AmigaE, abstract methods are supported but interfaces are not.


<syntaxhighlight lang=amigae>
<syntaxhighlight lang="amigae">
OBJECT fruit
OBJECT fruit
ENDOBJECT
ENDOBJECT
Line 232: Line 230:


=={{header|Apex}}==
=={{header|Apex}}==
<syntaxhighlight lang=apex>
<syntaxhighlight lang="apex">
// Interface
// Interface
public interface PurchaseOrder {
public interface PurchaseOrder {
Line 260: Line 258:
=={{header|Argile}}==
=={{header|Argile}}==
{{works with|Argile|1.0.0}}
{{works with|Argile|1.0.0}}
<syntaxhighlight lang=Argile>use std
<syntaxhighlight lang="argile">use std


(: abstract class :)
(: abstract class :)
Line 300: Line 298:




{{omit from|ARM Assembly}}


=={{header|AutoHotkey}}==
=={{header|AutoHotkey}}==
{{works with | AutoHotkey_L}}
{{works with | AutoHotkey_L}}
<syntaxhighlight lang=AutoHotkey>color(r, g, b){
<syntaxhighlight lang="autohotkey">color(r, g, b){
static color
static color
If !color
If !color
Line 338: Line 335:
{{works with|BBC BASIC for Windows}}
{{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:
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"
<syntaxhighlight lang="bbcbasic"> INSTALL @lib$+"CLASSLIB"
REM Declare a class with no implementation:
REM Declare a class with no implementation:
Line 359: Line 356:
==={{header|QB64}}===
==={{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:
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
<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.
'said, the following is both legal and executable.


Line 423: Line 420:
{{works with|QuickBasic|4.5}}
{{works with|QuickBasic|4.5}}
{{trans|QB64}}
{{trans|QB64}}
<syntaxhighlight lang=qbasic>a = 15
<syntaxhighlight lang="qbasic">a = 15
TYPE c
TYPE c
Line 455: Line 452:


The header file for the abstract class, interfaceAbs.h
The header file for the abstract class, interfaceAbs.h
<syntaxhighlight lang=c>#ifndef INTERFACE_ABS
<syntaxhighlight lang="c">#ifndef INTERFACE_ABS
#define INTERFACE_ABS
#define INTERFACE_ABS


Line 491: Line 488:
the code is in file silly.h. Note the actual structure of the class is not provided
the code is in file silly.h. Note the actual structure of the class is not provided
here. We don't want it visible.
here. We don't want it visible.
<syntaxhighlight lang=c>#ifndef SILLY_H
<syntaxhighlight lang="c">#ifndef SILLY_H
#define SILLY_H
#define SILLY_H
#include "intefaceAbs.h"
#include "intefaceAbs.h"
Line 503: Line 500:
Ok. Now it is necessary to provide the implementation of the realizable class.
Ok. Now it is necessary to provide the implementation of the realizable class.
This code should be in silly.c.
This code should be in silly.c.
<syntaxhighlight lang=c>#include "silly.h"
<syntaxhighlight lang="c">#include "silly.h"
#include <string.h>
#include <string.h>
#include <stdio.h>
#include <stdio.h>
Line 550: Line 547:


Now all's left is some example code that uses all this stuff.
Now all's left is some example code that uses all this stuff.
<syntaxhighlight lang=c>#include <stdio.h>
<syntaxhighlight lang="c">#include <stdio.h>
#include "silly.h"
#include "silly.h"


Line 566: Line 563:


=={{header|C sharp|C#}}==
=={{header|C sharp|C#}}==
<syntaxhighlight lang=csharp>abstract class Class1
<syntaxhighlight lang="csharp">abstract class Class1
{
{
public abstract void method1();
public abstract void method1();
Line 578: Line 575:
=={{header|C++}}==
=={{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.
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 {
<syntaxhighlight lang="cpp">class Abs {
public:
public:
virtual int method1(double value) = 0;
virtual int method1(double value) = 0;
Line 591: Line 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.
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 ]
<syntaxhighlight lang="cos">Class Abstract.Class.Shape [ Abstract ]
{
{
Parameter SHAPE = 1;
Parameter SHAPE = 1;
Line 609: Line 606:
Data type classes differ because they cannot contain properties, see example below.
Data type classes differ because they cannot contain properties, see example below.


<syntaxhighlight lang=cos>Class Abstract.DataType.Shape [ ClassType = datatype ]
<syntaxhighlight lang="cos">Class Abstract.DataType.Shape [ ClassType = datatype ]
{
{
Parameter SHAPE = 1;
Parameter SHAPE = 1;
Line 641: Line 638:
Using defprotocol, we can define what is essentially an interface.
Using defprotocol, we can define what is essentially an interface.


<syntaxhighlight lang=lisp>(defprotocol Foo (foo [this]))</syntaxhighlight>
<syntaxhighlight lang="lisp">(defprotocol Foo (foo [this]))</syntaxhighlight>


=={{header|COBOL}}==
=={{header|COBOL}}==
===Interface===
===Interface===
{{trans|F#}}
{{trans|F#}}
<syntaxhighlight lang=cobol> INTERFACE-ID. Shape.
<syntaxhighlight lang="cobol"> INTERFACE-ID. Shape.
PROCEDURE DIVISION.
PROCEDURE DIVISION.
Line 709: Line 706:
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.
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)
<syntaxhighlight lang="lisp">(defgeneric kar (kons)
(:documentation "Return the kar of a kons."))
(:documentation "Return the kar of a kons."))


Line 725: Line 722:
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.
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))
<syntaxhighlight lang="lisp">(defmethod kar ((cons cons))
(car cons))
(car cons))


Line 738: Line 735:
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>.
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))
<syntaxhighlight lang="lisp">(defmethod kar ((n integer))
1)
1)


Line 751: Line 748:


=={{header|Component Pascal}}==
=={{header|Component Pascal}}==
<syntaxhighlight lang=oberon2>
<syntaxhighlight lang="oberon2">
(* Abstract type *)
(* Abstract type *)
Object = POINTER TO ABSTRACT RECORD END;
Object = POINTER TO ABSTRACT RECORD END;
Line 765: Line 762:
</syntaxhighlight>
</syntaxhighlight>
...
...
<syntaxhighlight lang=oberon2>
<syntaxhighlight lang="oberon2">
(* Abstract method of Object *)
(* Abstract method of Object *)
PROCEDURE (dn: Object) Show*, NEW, ABSTRACT;
PROCEDURE (dn: Object) Show*, NEW, ABSTRACT;
Line 786: Line 783:


=={{header|Crystal}}==
=={{header|Crystal}}==
<syntaxhighlight lang=ruby>abstract class Animal # only abstract class can have abstract methods
<syntaxhighlight lang="ruby">abstract class Animal # only abstract class can have abstract methods
abstract def move
abstract def move
abstract def think
abstract def think
Line 829: Line 826:


=={{header|D}}==
=={{header|D}}==
<syntaxhighlight lang=d>import std.stdio;
<syntaxhighlight lang="d">import std.stdio;


class Foo {
class Foo {
Line 860: Line 857:
Abstract Class introduced in Delphi 2006. An abstract class cannot be instantiated and must be derived from in order to be used.
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)
<syntaxhighlight lang="delphi">TSomeClass = class abstract (TObject)
...
...
end;</syntaxhighlight>
end;</syntaxhighlight>
Line 867: Line 864:
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.
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
<syntaxhighlight lang="delphi">type
TMyObject = class(TObject)
TMyObject = class(TObject)
public
public
Line 893: Line 890:
A simple abstract type without enforcement can be created using the interface expression:
A simple abstract type without enforcement can be created using the interface expression:


<syntaxhighlight lang=e>interface Foo {
<syntaxhighlight lang="e">interface Foo {
to bar(a :int, b :int)
to bar(a :int, b :int)
}</syntaxhighlight>
}</syntaxhighlight>
Line 899: Line 896:
With enforcement, a separate ''stamp'' is created which must be applied to the instances. This is analogous to a Java interface.
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 {
<syntaxhighlight lang="e">interface Foo guards FooStamp {
to bar(a :int, b :int)
to bar(a :int, b :int)
}
}
Line 911: Line 908:
=={{header|Eiffel}}==
=={{header|Eiffel}}==


<syntaxhighlight lang=Eiffel>
<syntaxhighlight lang="eiffel">
deferred class
deferred class
AN_ABSTRACT_CLASS
AN_ABSTRACT_CLASS
Line 932: Line 929:


A more expressive view of an Abstract type in Eiffel:
A more expressive view of an Abstract type in Eiffel:
<syntaxhighlight lang=eiffel>
<syntaxhighlight lang="eiffel">
note
note
title: "Prototype Person"
title: "Prototype Person"
Line 997: Line 994:
=={{header|Elena}}==
=={{header|Elena}}==


<syntaxhighlight lang=elena>abstract class Bike
<syntaxhighlight lang="elena">abstract class Bike
{
{
abstract run();
abstract run();
Line 1,005: Line 1,002:
=={{header|F Sharp|F#}}==
=={{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:
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 =
<syntaxhighlight lang="fsharp">type Shape =
abstract Perimeter: unit -> float
abstract Perimeter: unit -> float
abstract Area: unit -> float
abstract Area: unit -> float
Line 1,015: Line 1,012:


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:
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>]
<syntaxhighlight lang=" fsharp">[<AbstractClass>]
type Bird() =
type Bird() =
// an abstract (=virtual) method with default impl.
// an abstract (=virtual) method with default impl.
Line 1,033: Line 1,030:


=={{header|Fantom}}==
=={{header|Fantom}}==
<syntaxhighlight lang=fantom>
<syntaxhighlight lang="fantom">
abstract class X
abstract class X
{
{
Line 1,068: Line 1,065:
{{trans|Fantom}}
{{trans|Fantom}}
There are numerous, mutually incompatible object oriented frameworks for Forth. This one works with the FOOS preprocessor extension of [[4tH]].
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
<syntaxhighlight lang="forth">include 4pp/lib/foos.4pp


:: X()
:: X()
Line 1,098: Line 1,095:
Needs the FMS-SI (single inheritance) library code located here:
Needs the FMS-SI (single inheritance) library code located here:
http://soton.mpeforth.com/flag/fms/index.html
http://soton.mpeforth.com/flag/fms/index.html
<syntaxhighlight lang=forth>include FMS-SI.f
<syntaxhighlight lang="forth">include FMS-SI.f


The FMS object extension uses duck typing and so has no need for abstract types.
The FMS object extension uses duck typing and so has no need for abstract types.
Line 1,105: Line 1,102:
=={{header|Fortran}}==
=={{header|Fortran}}==
Simple abstract derived type (i.e. abstract class) in Fortran 2008
Simple abstract derived type (i.e. abstract class) in Fortran 2008
<syntaxhighlight lang=fortran>
<syntaxhighlight lang="fortran">
! abstract derived type
! abstract derived type
type, abstract :: TFigure
type, abstract :: TFigure
Line 1,129: Line 1,126:
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 :-
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
<syntaxhighlight lang="freebasic">' FB 1.05.0 Win64


Type Animal Extends Object
Type Animal Extends Object
Line 1,181: Line 1,178:
=={{header|Genyris}}==
=={{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.
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()
<syntaxhighlight lang="genyris">class AbstractStack()
def .valid?(object) nil
def .valid?(object) nil


Line 1,187: Line 1,184:


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'':
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()
<syntaxhighlight lang="genyris">class StackInterface()
def .valid?(object)
def .valid?(object)
object
object
Line 1,197: Line 1,194:


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:
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)
<syntaxhighlight lang="genyris">class XYZstack(Object)
def .init()
def .init()
var .items ()
var .items ()
Line 1,207: Line 1,204:
tmp</syntaxhighlight>
tmp</syntaxhighlight>
Now we can tag an object that conforms to the Interface:
Now we can tag an object that conforms to the Interface:
<syntaxhighlight lang=genyris>tag StackInterface (XYZstack(.new))</syntaxhighlight>
<syntaxhighlight lang="genyris">tag StackInterface (XYZstack(.new))</syntaxhighlight>


=={{header|Go}}==
=={{header|Go}}==
Line 1,216: Line 1,213:
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.
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
<syntaxhighlight lang="go">package main


import "fmt"
import "fmt"
Line 1,269: Line 1,266:


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).
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 {
<syntaxhighlight lang="groovy">public interface Interface {
int method1(double value)
int method1(double value)
int method2(String name)
int method2(String name)
Line 1,276: Line 1,273:


An abstract class may implement some of its methods and leave others unimplemented. The unimplemented methods and the class itself must be declared "abstract".
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 {
<syntaxhighlight lang="groovy">public abstract class Abstract1 {
abstract public int methodA(Date value)
abstract public int methodA(Date value)
abstract protected int methodB(String name)
abstract protected int methodB(String name)
Line 1,283: Line 1,280:


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.
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 {
<syntaxhighlight lang="groovy">public abstract class Abstract2 implements Interface {
int add(int a, int b) { a + b }
int add(int a, int b) { a + b }
}</syntaxhighlight>
}</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.
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 {
<syntaxhighlight lang="groovy">public class Concrete1 implements Interface {
public int method1(double value) { value as int }
public int method1(double value) { value as int }
public int method2(String name) { (! name) ? 0 : name.toList().collect { it as char }.sum() }
public int method2(String name) { (! name) ? 0 : name.toList().collect { it as char }.sum() }
Line 1,307: Line 1,304:


Obligatory test:
Obligatory test:
<syntaxhighlight lang=groovy>def c1 = new Concrete1()
<syntaxhighlight lang="groovy">def c1 = new Concrete1()
assert c1 instanceof Interface
assert c1 instanceof Interface
println (new Concrete1().method2("Superman"))
println (new Concrete1().method2("Superman"))
Line 1,332: Line 1,329:


For example, the built-in type class Eq (the types that can be compared for equality) can be declared as follows:
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
<syntaxhighlight lang="haskell">class Eq a where
(==) :: a -> a -> Bool
(==) :: a -> a -> Bool
(/=) :: a -> a -> Bool</syntaxhighlight>
(/=) :: a -> a -> Bool</syntaxhighlight>


Default implementations of the functions can be provided:
Default implementations of the functions can be provided:
<syntaxhighlight lang=haskell>class Eq a where
<syntaxhighlight lang="haskell">class Eq a where
(==) :: a -> a -> Bool
(==) :: a -> a -> Bool
(/=) :: a -> a -> Bool
(/=) :: a -> a -> Bool
Line 1,345: Line 1,342:


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:
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
<syntaxhighlight lang="haskell">func :: (Eq a) => a -> Bool
func x = x == x</syntaxhighlight>
func x = x == x</syntaxhighlight>


Suppose I make a new type
Suppose I make a new type
<syntaxhighlight lang=haskell>data Foo = Foo {x :: Integer, str :: String}</syntaxhighlight>
<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
One could then provide an implementation ("instance") the type class Eq with this type
<syntaxhighlight lang=haskell>instance Eq Foo where
<syntaxhighlight lang="haskell">instance Eq Foo where
(Foo x1 str1) == (Foo x2 str2) =
(Foo x1 str1) == (Foo x2 str2) =
(x1 == x2) && (str1 == str2)</syntaxhighlight>
(x1 == x2) && (str1 == str2)</syntaxhighlight>
Line 1,362: Line 1,359:
An abstract class is a class with abstract methods. Icon is not object-oriented.
An abstract class is a class with abstract methods. Icon is not object-oriented.


<syntaxhighlight lang=unicon>class abstraction()
<syntaxhighlight lang="unicon">class abstraction()
abstract method compare(l,r) # generates runerr(700, "method compare()")
abstract method compare(l,r) # generates runerr(700, "method compare()")
end</syntaxhighlight>
end</syntaxhighlight>
Line 1,380: Line 1,377:
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.
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.


<syntaxhighlight lang=java>public abstract class Abs {
<syntaxhighlight lang="java">public abstract class Abs {
public abstract int method1(double value);
public abstract int method1(double value);
protected abstract int method2(String name);
protected abstract int method2(String name);
Line 1,388: Line 1,385:
}</syntaxhighlight>
}</syntaxhighlight>
Before Java 8, interfaces could not implement any methods and all methods were implicitly public and abstract.
Before Java 8, interfaces could not implement any methods and all methods were implicitly public and abstract.
<syntaxhighlight lang=java>public interface Inter {
<syntaxhighlight lang="java">public interface Inter {
int method1(double value);
int method1(double value);
int method2(String name);
int method2(String name);
Line 1,398: Line 1,395:


Usage:
Usage:
<syntaxhighlight lang=julia>abstract type «name» end
<syntaxhighlight lang="julia">abstract type «name» end
abstract type «name» <: «supertype» end</syntaxhighlight>
abstract type «name» <: «supertype» end</syntaxhighlight>


Examples:
Examples:
<syntaxhighlight lang=julia>abstract type Number end
<syntaxhighlight lang="julia">abstract type Number end
abstract type Real <: Number end
abstract type Real <: Number end
abstract type FloatingPoint <: Real end
abstract type FloatingPoint <: Real end
Line 1,415: Line 1,412:


Here's a very simple (and silly) example of both:
Here's a very simple (and silly) example of both:
<syntaxhighlight lang=scala>// version 1.1
<syntaxhighlight lang="scala">// version 1.1


interface Announcer {
interface Announcer {
Line 1,484: Line 1,481:
=={{header|Lasso}}==
=={{header|Lasso}}==
Instead of abstract classes or interfaces, Lasso uses a [http://lassoguide.com/language/types.html trait system].
Instead of abstract classes or interfaces, Lasso uses a [http://lassoguide.com/language/types.html trait system].
<syntaxhighlight lang=lasso>define abstract_trait => trait {
<syntaxhighlight lang="lasso">define abstract_trait => trait {
require get(index::integer)
require get(index::integer)
Line 1,519: Line 1,516:


In some movie script:
In some movie script:
<syntaxhighlight lang=lingo>on extendAbstractClass (instance, abstractClass)
<syntaxhighlight lang="lingo">on extendAbstractClass (instance, abstractClass)
-- 'raw' instance of abstract class is made parent ("ancestor") of the
-- 'raw' instance of abstract class is made parent ("ancestor") of the
-- passed instance, i.e. the passed instance extends the abstract class
-- passed instance, i.e. the passed instance extends the abstract class
Line 1,526: Line 1,523:


Parent script "AbstractClass":
Parent script "AbstractClass":
<syntaxhighlight lang=lingo>-- instantiation of abstract class by calling its constructor fails
<syntaxhighlight lang="lingo">-- instantiation of abstract class by calling its constructor fails
on new (me)
on new (me)
-- optional: show error message as alert
-- optional: show error message as alert
Line 1,540: Line 1,537:


Parent script "MyClass"
Parent script "MyClass"
<syntaxhighlight lang=lingo>property ringtone
<syntaxhighlight lang="lingo">property ringtone


on new (me)
on new (me)
Line 1,553: Line 1,550:


Usage:
Usage:
<syntaxhighlight lang=lingo>obj = script("MyClass").new()
<syntaxhighlight lang="lingo">obj = script("MyClass").new()
obj.ring(3)
obj.ring(3)
-- "Bell"
-- "Bell"
Line 1,567: Line 1,564:


In some movie script:
In some movie script:
<syntaxhighlight lang=lingo>on implementsInterface (instance, interfaceClass)
<syntaxhighlight lang="lingo">on implementsInterface (instance, interfaceClass)
interfaceFuncs = interfaceClass.handlers()
interfaceFuncs = interfaceClass.handlers()
funcs = instance.handlers()
funcs = instance.handlers()
Line 1,582: Line 1,579:
Parent script "InterfaceClass":
Parent script "InterfaceClass":
(Note: in Lingo closing function definitions with "end" is optional, so this a valid definition of 3 empty functions)
(Note: in Lingo closing function definitions with "end" is optional, so this a valid definition of 3 empty functions)
<syntaxhighlight lang=lingo>on foo
<syntaxhighlight lang="lingo">on foo
on bar
on bar
on foobar</syntaxhighlight>
on foobar</syntaxhighlight>


Parent script "MyClass":
Parent script "MyClass":
<syntaxhighlight lang=lingo>on new (me)
<syntaxhighlight lang="lingo">on new (me)
-- if this class doesn't implement all functions of the
-- if this class doesn't implement all functions of the
-- interface class, instantiation fails
-- interface class, instantiation fails
Line 1,609: Line 1,606:


Usage:
Usage:
<syntaxhighlight lang=lingo>obj = script("MyClass").new()
<syntaxhighlight lang="lingo">obj = script("MyClass").new()
put obj -- would show <Void> if interface is not fully implemented
put obj -- would show <Void> if interface is not fully implemented
-- <offspring "MyClass" 2 171868></syntaxhighlight>
-- <offspring "MyClass" 2 171868></syntaxhighlight>
Line 1,617: Line 1,614:


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".
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>
<syntaxhighlight lang="logtalk">
:- protocol(datep).
:- protocol(datep).


Line 1,631: Line 1,628:
=={{header|Lua}}==
=={{header|Lua}}==
Lua does not include built-in object oriented paradigms. These features can be added using simple code such as the following:
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 = {}
<syntaxhighlight lang="lua">BaseClass = {}


function class ( baseClass )
function class ( baseClass )
Line 1,666: Line 1,663:
BaseClass.abstractClass = abstractClass</syntaxhighlight>
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:
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
<syntaxhighlight lang="lua">A = class() -- New class A inherits BaseClass by default
AA = A:class() -- New class AA inherits from existing class A
AA = A:class() -- New class AA inherits from existing class A
B = abstractClass() -- New abstract class B
B = abstractClass() -- New abstract class B
Line 1,677: Line 1,674:
=={{header|M2000 Interpreter}}==
=={{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"
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 {
<syntaxhighlight lang="m2000 interpreter">Class BaseState {
Private:
Private:
      x as double=1212, z1 as currency=1000, k$="ok"
      x as double=1212, z1 as currency=1000, k$="ok"
Line 1,745: Line 1,742:
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:
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>
<syntaxhighlight lang="mathematica">
(* Define an interface, Foo, which requires that the functions Foo, Bar, and Baz be defined *)
(* 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]];
InterfaceFooQ[obj_] := ValueQ[Foo[obj]] && ValueQ[Bar[obj]] && ValueQ[Baz[obj]];
Line 1,792: Line 1,789:
=={{header|MATLAB}}==
=={{header|MATLAB}}==
; Abstract Class
; Abstract Class
<syntaxhighlight lang=MATLAB>classdef (Abstract) AbsClass
<syntaxhighlight lang="matlab">classdef (Abstract) AbsClass
...
...
end</syntaxhighlight>
end</syntaxhighlight>
Line 1,800: Line 1,797:
When you define any abstract methods or properties, MATLAB® automatically sets the class Abstract attribute to true.
When you define any abstract methods or properties, MATLAB® automatically sets the class Abstract attribute to true.
; Abstract Methods
; Abstract Methods
<syntaxhighlight lang=MATLAB>methods (Abstract)
<syntaxhighlight lang="matlab">methods (Abstract)
abstMethod(obj)
abstMethod(obj)
end</syntaxhighlight>
end</syntaxhighlight>
Line 1,808: Line 1,805:
* 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.
* 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
; Abstract Properties
<syntaxhighlight lang=MATLAB>properties (Abstract)
<syntaxhighlight lang="matlab">properties (Abstract)
AbsProp
AbsProp
end</syntaxhighlight>
end</syntaxhighlight>
Line 1,832: Line 1,829:
these features by default for all tpyes.
these features by default for all tpyes.


<syntaxhighlight lang=Mercury>:- module eq.
<syntaxhighlight lang="mercury">:- module eq.
:- interface.
:- interface.


Line 1,860: Line 1,857:


=={{header|Nemerle}}==
=={{header|Nemerle}}==
<syntaxhighlight lang=Nemerle>using System.Console;
<syntaxhighlight lang="nemerle">using System.Console;


namespace RosettaCode
namespace RosettaCode
Line 1,900: Line 1,897:


=={{header|NetRexx}}==
=={{header|NetRexx}}==
<syntaxhighlight lang=NetRexx>/* NetRexx */
<syntaxhighlight lang="netrexx">/* NetRexx */
options replace format comments java crossref symbols binary
options replace format comments java crossref symbols binary


Line 1,987: Line 1,984:
=={{header|newLISP}}==
=={{header|newLISP}}==


<syntaxhighlight lang=newLISP>; file: abstract.lsp
<syntaxhighlight lang="newlisp">; file: abstract.lsp
; url: http://rosettacode.org/wiki/Abstract_type
; url: http://rosettacode.org/wiki/Abstract_type
; author: oofoe 2012-01-28
; author: oofoe 2012-01-28
Line 2,052: Line 2,049:
=={{header|Nim}}==
=={{header|Nim}}==
In Nim type classes can be seen as an abstract type. Type classes specify interfaces, which can be instantiated by concrete types.
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
<syntaxhighlight lang="nim">type
Comparable = concept x, y
Comparable = concept x, y
(x < y) is bool
(x < y) is bool
Line 2,069: Line 2,066:
Source: [https://github.com/nitlang/nit/blob/master/examples/rosettacode/abstract_type.nit the official Nit’s repository]
Source: [https://github.com/nitlang/nit/blob/master/examples/rosettacode/abstract_type.nit the official Nit’s repository]


<syntaxhighlight lang=nit># Task: abstract type
<syntaxhighlight lang="nit"># Task: abstract type
#
#
# Methods without implementation are annotated `abstract`.
# Methods without implementation are annotated `abstract`.
Line 2,090: Line 2,087:
=={{header|Oberon-2}}==
=={{header|Oberon-2}}==
{{Works with|oo2c Version 2}}
{{Works with|oo2c Version 2}}
<syntaxhighlight lang=oberon2>
<syntaxhighlight lang="oberon2">
TYPE
TYPE
Animal = POINTER TO AnimalDesc;
Animal = POINTER TO AnimalDesc;
Line 2,101: Line 2,098:


=={{header|Objeck}}==
=={{header|Objeck}}==
<syntaxhighlight lang=objeck>
<syntaxhighlight lang="objeck">
class ClassA {
class ClassA {
method : virtual : public : MethodA() ~ Int;
method : virtual : public : MethodA() ~ Int;
Line 2,117: Line 2,114:
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''':
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 =
<syntaxhighlight lang="ocaml">class virtual foo =
object
object
method virtual bar : int
method virtual bar : int
Line 2,125: Line 2,122:


In OCaml what we call an abstract type is not OO related, it is only a type defined without definition, for example:
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>
<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.
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:
Example of abstracting a type in an interface:
<syntaxhighlight lang=ocaml>module Foo : sig
<syntaxhighlight lang="ocaml">module Foo : sig
type t
type t
end = struct
end = struct
Line 2,136: Line 2,133:


Pure abstract types in the implementation:
Pure abstract types in the implementation:
<syntaxhighlight lang=ocaml>type u
<syntaxhighlight lang="ocaml">type u
type v
type v
type 'a t
type 'a t
Line 2,150: Line 2,147:
Unlike interfaces, properties can include method implementations and attributes (see lang/Comparable.of for instance).
Unlike interfaces, properties can include method implementations and attributes (see lang/Comparable.of for instance).


<syntaxhighlight lang=Oforth>Property new: Spherical(r)
<syntaxhighlight lang="oforth">Property new: Spherical(r)
Spherical method: radius @r ;
Spherical method: radius @r ;
Spherical method: setRadius := r ;
Spherical method: setRadius := r ;
Line 2,165: Line 2,162:


Usage :
Usage :
<syntaxhighlight lang=Oforth>: testProperty
<syntaxhighlight lang="oforth">: testProperty
| b p |
| b p |
Ballon new($red, 0.1) ->b
Ballon new($red, 0.1) ->b
Line 2,191: Line 2,188:


===Interface===
===Interface===
<syntaxhighlight lang=ooRexx> -- Example showing a class that defines an interface in ooRexx
<syntaxhighlight lang="oorexx"> -- Example showing a class that defines an interface in ooRexx
-- shape is the interface class that defines the methods a shape instance
-- shape is the interface class that defines the methods a shape instance
-- is expected to implement as abstract methods. Instances of the shape
-- is expected to implement as abstract methods. Instances of the shape
Line 2,266: Line 2,263:


===Abstract Type===
===Abstract Type===
<syntaxhighlight lang=ooRexx> -- Example showing an abstract type in ooRexx
<syntaxhighlight lang="oorexx"> -- Example showing an abstract type in ooRexx
-- shape is the abstract class that defines the abstract method area
-- shape is the abstract class that defines the abstract method area
-- which is then implemented by its two subclasses, rectangle and circle
-- which is then implemented by its two subclasses, rectangle and circle
Line 2,366: Line 2,363:
There are no abstract types as part of the language, but we can do as in Python and raise exceptions:
There are no abstract types as part of the language, but we can do as in Python and raise exceptions:


<syntaxhighlight lang=oz>declare
<syntaxhighlight lang="oz">declare
class BaseQueue
class BaseQueue
attr
attr
Line 2,400: Line 2,397:
=={{header|Perl}}==
=={{header|Perl}}==


<syntaxhighlight lang=perl>package AbstractFoo;
<syntaxhighlight lang="perl">package AbstractFoo;


use strict;
use strict;
Line 2,416: Line 2,413:
Since Perl 5.12, the Yadda Yadda operator (...) dies with an Unimplemented error,
Since Perl 5.12, the Yadda Yadda operator (...) dies with an Unimplemented error,


<syntaxhighlight lang=perl>
<syntaxhighlight lang="perl">
package AbstractFoo;
package AbstractFoo;
Line 2,433: Line 2,430:
Raku inspired roles are provided by the [http://search.cpan.org/perldoc?Moose Moose] library
Raku inspired roles are provided by the [http://search.cpan.org/perldoc?Moose Moose] library


<syntaxhighlight lang=perl>package AbstractFoo;
<syntaxhighlight lang="perl">package AbstractFoo;


use Moose::Role;
use Moose::Role;
Line 2,447: Line 2,444:
Roles are also provided in a more lightweight form with [http://search.cpan.org/perldoc?Role::Tiny Role::Tiny] library
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;
<syntaxhighlight lang="perl">package AbstractFoo;


use Role::Tiny;
use Role::Tiny;
Line 2,465: Line 2,462:


You can also have explicitly abstract classes (and/or abstract methods). Needs 0.8.1+
You can also have explicitly abstract classes (and/or abstract methods). Needs 0.8.1+
<!--<syntaxhighlight lang=Phix>-->
<!--<syntaxhighlight lang="phix">-->
<span style="color: #008080;">abstract</span> <span style="color: #008080;">class</span> <span style="color: #000000;">job</span>
<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>
<span style="color: #004080;">integer</span> <span style="color: #000000;">id</span>
Line 2,489: Line 2,486:


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
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 {
<syntaxhighlight lang="php">abstract class Abs {
abstract public function method1($value);
abstract public function method1($value);
abstract protected function method2($name);
abstract protected function method2($name);
Line 2,497: Line 2,494:
}</syntaxhighlight>
}</syntaxhighlight>
Interfaces in PHP may not implement any methods and all methods are public and implicitly abstract.
Interfaces in PHP may not implement any methods and all methods are public and implicitly abstract.
<syntaxhighlight lang=php>interface Inter {
<syntaxhighlight lang="php">interface Inter {
public function method1($value);
public function method1($value);
public function method2($name);
public function method2($name);
Line 2,504: Line 2,501:


=={{header|PicoLisp}}==
=={{header|PicoLisp}}==
<syntaxhighlight lang=PicoLisp># In PicoLisp there is no formal difference between abstract and concrete classes.
<syntaxhighlight lang="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
# There is just a naming convention where abstract classes start with a
# lower-case character after the '+' (the naming convention for classes).
# lower-case character after the '+' (the naming convention for classes).
Line 2,517: Line 2,514:


=={{header|PowerShell}}==
=={{header|PowerShell}}==
<syntaxhighlight lang=PowerShell>
<syntaxhighlight lang="powershell">
#Requires -Version 5.0
#Requires -Version 5.0


Line 2,612: Line 2,609:
</syntaxhighlight>
</syntaxhighlight>
Create a new player:
Create a new player:
<syntaxhighlight lang=PowerShell>
<syntaxhighlight lang="powershell">
$player1 = [Player]::new("sam bradford", "philadelphia eagles", "qb", 7)
$player1 = [Player]::new("sam bradford", "philadelphia eagles", "qb", 7)
$player1
$player1
Line 2,623: Line 2,620:
</pre>
</pre>
Trade the player:
Trade the player:
<syntaxhighlight lang=PowerShell>
<syntaxhighlight lang="powershell">
$player1.Trade("minnesota vikings", 8)
$player1.Trade("minnesota vikings", 8)
$player1
$player1
Line 2,634: Line 2,631:
</pre>
</pre>
Create a new player:
Create a new player:
<syntaxhighlight lang=PowerShell>
<syntaxhighlight lang="powershell">
$player2 = [Player]::new("demarco murray", "philadelphia eagles", "rb", 29)
$player2 = [Player]::new("demarco murray", "philadelphia eagles", "rb", 29)
$player2
$player2
Line 2,645: Line 2,642:
</pre>
</pre>
Trade the player:
Trade the player:
<syntaxhighlight lang=PowerShell>
<syntaxhighlight lang="powershell">
$player2.Trade("tennessee titans")
$player2.Trade("tennessee titans")
$player2
$player2
Line 2,658: Line 2,655:
=={{header|Python}}==
=={{header|Python}}==


<syntaxhighlight lang=python>class BaseQueue(object):
<syntaxhighlight lang="python">class BaseQueue(object):
"""Abstract/Virtual Class
"""Abstract/Virtual Class
"""
"""
Line 2,683: Line 2,680:


Starting from Python 2.6, abstract classes can be created using the standard abc module:
Starting from Python 2.6, abstract classes can be created using the standard abc module:
<syntaxhighlight lang=python>from abc import ABCMeta, abstractmethod
<syntaxhighlight lang="python">from abc import ABCMeta, abstractmethod


class BaseQueue():
class BaseQueue():
Line 2,707: Line 2,704:
=={{header|Racket}}==
=={{header|Racket}}==


<syntaxhighlight lang=racket>
<syntaxhighlight lang="racket">
#lang racket
#lang racket


Line 2,729: Line 2,726:
Raku supports roles, which are a bit like interfaces, but unlike interfaces in Java they can also contain some implementation.
Raku supports roles, which are a bit like interfaces, but unlike interfaces in Java they can also contain some implementation.


<syntaxhighlight lang=perl6>
<syntaxhighlight lang="raku" line>
use v6;
use v6;


Line 2,756: Line 2,753:


=={{header|REBOL}}==
=={{header|REBOL}}==
<syntaxhighlight lang=REBOL>REBOL [
<syntaxhighlight lang="rebol">REBOL [
Title: "Abstract Type"
Title: "Abstract Type"
URL: http://rosettacode.org/wiki/Abstract_type
URL: http://rosettacode.org/wiki/Abstract_type
Line 2,802: Line 2,799:


=={{header|Red}}==
=={{header|Red}}==
<syntaxhighlight lang=Red>Red [
<syntaxhighlight lang="red">Red [
Title: "Abstract Type"
Title: "Abstract Type"
Original-Author: oofoe
Original-Author: oofoe
Line 2,850: Line 2,847:
=={{header|ReScript}}==
=={{header|ReScript}}==
Here is an abstract type definition:
Here is an abstract type definition:
<syntaxhighlight lang=ReScript>type t</syntaxhighlight>
<syntaxhighlight lang="rescript">type t</syntaxhighlight>


=={{header|REXX}}==
=={{header|REXX}}==
Line 2,861: Line 2,858:
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:
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'
<syntaxhighlight lang="ruby">require 'abstraction'


class AbstractQueue
class AbstractQueue
Line 2,899: Line 2,896:
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:
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 {
<syntaxhighlight lang="rust">trait Shape {
fn area(self) -> i32;
fn area(self) -> i32;
}</syntaxhighlight>
}</syntaxhighlight>
Line 2,905: Line 2,902:
The trait can then be implemented on a struct.
The trait can then be implemented on a struct.


<syntaxhighlight lang=rust>struct Square {
<syntaxhighlight lang="rust">struct Square {
side_length: i32
side_length: i32
}
}
Line 2,917: Line 2,914:
Note, traits can also have a default implementation:
Note, traits can also have a default implementation:


<syntaxhighlight lang=rust>trait Shape {
<syntaxhighlight lang="rust">trait Shape {
fn area(self) -> i32;
fn area(self) -> i32;


Line 2,939: Line 2,936:
different meaning that described in this page. Here are some examples:
different meaning that described in this page. Here are some examples:


<syntaxhighlight lang=scala>abstract class X {
<syntaxhighlight lang="scala">abstract class X {
type A
type A
var B: A
var B: A
Line 2,961: Line 2,958:
A function is automaticall attached to the interface, when it has an parameter of the interface type.
A function is automaticall attached to the interface, when it has an parameter of the interface type.


<syntaxhighlight lang=seed7>
<syntaxhighlight lang="seed7">
const type: myInterf is sub object interface;
const type: myInterf is sub object interface;


Line 2,971: Line 2,968:
=={{header|Sidef}}==
=={{header|Sidef}}==
{{trans|Raku}}
{{trans|Raku}}
<syntaxhighlight lang=ruby>class A {
<syntaxhighlight lang="ruby">class A {
# must be filled in by the class which will inherit it
# must be filled in by the class which will inherit it
method abstract() { die 'Unimplemented' };
method abstract() { die 'Unimplemented' };
Line 2,992: Line 2,989:
Abtract Datatypes are declared using the VIRTUAL keyword.
Abtract Datatypes are declared using the VIRTUAL keyword.
For example, we need the following two procedures hash and equalto for a hash map implementation.
For example, we need the following two procedures hash and equalto for a hash map implementation.
<syntaxhighlight lang=simula>
<syntaxhighlight lang="simula">
! ABSTRACT HASH KEY TYPE ;
! ABSTRACT HASH KEY TYPE ;
LISTVAL CLASS HASHKEY;
LISTVAL CLASS HASHKEY;
Line 3,004: Line 3,001:
</syntaxhighlight>
</syntaxhighlight>
A concrete implementation can be derived as follows:
A concrete implementation can be derived as follows:
<syntaxhighlight lang=simula>
<syntaxhighlight lang="simula">
! COMMON HASH KEY TYPE IS TEXT ;
! COMMON HASH KEY TYPE IS TEXT ;
HASHKEY CLASS TEXTHASHKEY(T); VALUE T; TEXT T;
HASHKEY CLASS TEXTHASHKEY(T); VALUE T; TEXT T;
Line 3,028: Line 3,025:
=={{header|Smalltalk}}==
=={{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):
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
<syntaxhighlight lang="smalltalk">someClass class >> isAbstract
^ true
^ true


Line 3,051: Line 3,048:


Here is an example signature for a queue data structure:
Here is an example signature for a queue data structure:
<syntaxhighlight lang=sml>signature QUEUE = sig
<syntaxhighlight lang="sml">signature QUEUE = sig
type 'a queue
type 'a queue
val empty : 'a queue
val empty : 'a queue
Line 3,061: Line 3,058:
will be abstract if we use opaque ascription. Instead we could create a version of the signature which specifies 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:
in which case it will never be abstract:
<syntaxhighlight lang=sml>signature LIST_QUEUE = sig
<syntaxhighlight lang="sml">signature LIST_QUEUE = sig
type 'a queue = 'a list
type 'a queue = 'a list
val empty : 'a queue
val empty : 'a queue
Line 3,075: Line 3,072:


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...
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>oo::class create AbstractQueue {
<syntaxhighlight lang="tcl">oo::class create AbstractQueue {
method enqueue item {
method enqueue item {
error "not implemented"
error "not implemented"
Line 3,085: Line 3,082:
}</syntaxhighlight>
}</syntaxhighlight>


{{omit from|TorqueScript}}


=={{header|Vala}}==
=={{header|Vala}}==
<syntaxhighlight lang=vala>public abstract class Animal : Object {
<syntaxhighlight lang="vala">public abstract class Animal : Object {
public void eat() {
public void eat() {
print("Chomp! Chomp!\n");
print("Chomp! Chomp!\n");
Line 3,143: Line 3,139:
* By convention all abstract classes have one or more Protected constructors.
* By convention all abstract classes have one or more Protected constructors.


<syntaxhighlight lang=vbnet>MustInherit Class Base
<syntaxhighlight lang="vbnet">MustInherit Class Base


Protected Sub New()
Protected Sub New()
Line 3,165: Line 3,161:
Interfaces may contain Functions, Subroutines, Properties, and Events.
Interfaces may contain Functions, Subroutines, Properties, and Events.


<syntaxhighlight lang=vbnet>Interface IBase
<syntaxhighlight lang="vbnet">Interface IBase
Sub Method_Must_Be_Implemented()
Sub Method_Must_Be_Implemented()
End Interface</syntaxhighlight>
End Interface</syntaxhighlight>
Line 3,177: Line 3,173:
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.
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=vlang>interface Beast {
<syntaxhighlight lang="vlang">interface Beast {
kind() string
kind() string
name() string
name() string
Line 3,226: Line 3,222:


The Go example, when rewritten in Wren, looks like this.
The Go example, when rewritten in Wren, looks like this.
<syntaxhighlight lang=ecmascript>import "/fmt" for Fmt
<syntaxhighlight lang="ecmascript">import "/fmt" for Fmt


class Beast{
class Beast{
Line 3,268: Line 3,264:
=={{header|zkl}}==
=={{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.
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
<syntaxhighlight lang="zkl">class Stream{ // Mostly virtural base class
var [proxy protected]
var [proxy protected]
isBroken = fcn { _broken.isSet() },
isBroken = fcn { _broken.isSet() },
Line 3,293: Line 3,289:


And now for a "real" object:
And now for a "real" object:
<syntaxhighlight lang=zkl>class DevNull(Stream){
<syntaxhighlight lang="zkl">class DevNull(Stream){
var [const] fileName = "DevNull"; // compatibility with File
var [const] fileName = "DevNull"; // compatibility with File
fcn init { Stream.init() }
fcn init { Stream.init() }
Line 3,300: Line 3,296:




{{omit from|Applesoft BASIC}}
{{omit from|AArch64 Assembly}}
{{omit from|ALGOL 68}}
{{omit from|ALGOL 68}}
{{omit from|Applesoft BASIC}}
{{omit from|ARM Assembly}}
{{omit from|AWK}}
{{omit from|AWK}}
{{omit from|BASIC}}
{{omit from|BASIC}}
Line 3,309: Line 3,307:
{{omit from|Falcon|Does not support the concept of an abstract type.}}
{{omit from|Falcon|Does not support the concept of an abstract type.}}
{{omit from|gnuplot}}
{{omit from|gnuplot}}
{{omit from|Icon}}
{{omit from|Integer BASIC}}
{{omit from|Integer BASIC}}
{{omit from|J}}
{{omit from|JavaScript}}
{{omit from|JavaScript}}
{{omit from|Icon}}
{{omit from|J}}
{{omit from|LaTeX}}
{{omit from|LaTeX}}
{{omit from|M4}}
{{omit from|Make}}
{{omit from|Make}}
{{omit from|Maxima}}
{{omit from|Maxima}}
{{omit from|M4}}
{{omit from|Metafont}}
{{omit from|Metafont}}
{{omit from|MiniZinc|no ability to declare new types at all}}
{{omit from|ML/I}}
{{omit from|ML/I}}
{{omit from|Modula-2}}
{{omit from|Modula-2}}
Line 3,326: Line 3,325:
{{omit from|Scratch}}
{{omit from|Scratch}}
{{omit from|TI-89 BASIC|Does not have static or user-defined types.}}
{{omit from|TI-89 BASIC|Does not have static or user-defined types.}}
{{omit from|TorqueScript}}
{{omit from|UNIX Shell}}
{{omit from|UNIX Shell}}
{{omit from|ZX Spectrum Basic}}
{{omit from|ZX Spectrum Basic}}