Menu
Home Explore People Places Arts History Plants & Animals Science Life & Culture Technology
On this page
Comparison of programming languages (object-oriented programming)
List article

This comparison of programming languages compares how object-oriented programming languages such as C++, Java, Smalltalk, Object Pascal, Perl, Python, and others manipulate data structures.

Object construction and destruction

constructiondestruction
ABAP Objectsdata variable type ref to class .create object variable «exporting parameter = argument».123
APL (Dyalog)variable←⎕NEW class «parameters»⎕EX 'variable'
C++class variable«(parameters)»;4 orclass *variable = new class«(parameters)»;5delete pointer;
C#class variable = new class(parameters);variable.Dispose();6
Java7
Ddestroy(variable);
eCclass «instance handle» { «properties/data members assignments, instance method overrides» }delete instance handle;
Objective-C (Cocoa)class *variable = [[class alloc ] init]; or class *variable = [[class alloc ] initWithFoo:parameter «bar:parameter ...»];[variable release];
Swiftlet variable = class(parameters)
Pythonvariable = class(parameters)del variable8 (Normally not needed)
Visual Basic .NETDim variable As New class(parameters)variable.Dispose()9
XojoDim variable As New class(parameters)variable = Nil
Eiffelcreate variable orcreate «{TYPE}» variable.make_foo «(parameters)» orvariable := create {TYPE} orvariable := create {TYPE}.make_foo «(parameters)» 10
PHP$variable = new class«(parameters)»;unset($variable);11
Perl 5«my »$variable = class->new«(parameters)»;undef($variable);
Raku«my »$variable = class.new«(parameters)»;$variable.undefine;
Rubyvariable = class.new«(parameters)»12
Windows PowerShell$variable = New-Object «-TypeName» class ««-ArgumentList» parameters»Remove-Variable «-Name» variable
OCamllet variable = new class «parameters» or let variable = object members end1314
F#let variable = «new »class(«parameters»)
SmalltalkThe class is an Object.Just send a message to a class, usually #new or #new:, and many others, for example:Point x: 10 y: 20.Array with: -1 with: 3 with: 2.
JavaScriptvar variable = new class«(parameters)» or var variable = { «key1: value1«, key2: value2 ...»»}15
Object Pascal (Delphi)ClassVar := ClassType.ConstructorName(parameters);ClassVar.Free;
Scalaval obj = new Object // no parametersval obj = new Object(arg0, arg1, arg2...)val obj = Object(arg0, arg1, arg2...) // case classval obj = new Object(arg0, arg1, param1 = value1, ...) // named parameters16
COBOLINVOKE class "NEW" RETURNING variable orMOVE class::"NEW" TO variable
Cobravariable «as class» = class(parameters)variable.dispose
ISLISP(setq variable (create (class <some-class> [:field-1 value-1 [:field-2 value-2] ..])))17

Class declaration

classprotocolnamespace
ABAP Objectsclass name definition «inheriting from parentclass». «interfaces: interfaces.» method_and_field_declarations endclass.class name implementation. method_implementations endclass.interface name. members endinterface.
APL (Dyalog):Class name «:parentclass» «,interfaces»members:EndClass:Interface namemembers:EndInterface:Namespace namemembers:EndNamespace
C++class name« : public parentclasses18» { members };namespace name { members }
C#class name« : «parentclass»«, interfaces»» { members }interface name« : parentinterfaces» { members }
Dmodule name; members
eCclass name« : base class» { «default member values assignments» «members» }namespace name;
Javaclass name« extends parentclass»« implements interfaces» { members }interface name« extends parentinterfaces» { members }package name; members
PHPnamespace name; members
Objective-C@interface name« : parentclass»19«< protocols >» { instance_fields } method_and_property_declarations @end @implementation name method_implementations @end20@protocol name«< parentprotocols >» members @end21
Swiftclass name« : «parentclass»«, protocols»» { members }protocol name« : parentprotocols» { members }
Pythonclass name«(parentclasses22)»:Tab ↹ members23__all__ = [ member1,member2,... ]
Visual Basic .NETClass name« Inherits parentclass»« Implements interfaces»members End ClassInterface name« Inherits parentinterfaces»members End InterfaceNamespace namemembers End Namespace
XojoClass name« Inherits parentclass»« Implements interfaces»members End ClassInterface name« Inherits parentinterfaces»members End InterfaceModule namemembers End Module
Eiffelclass name« inherit parentclasses24»membersend
Perlpackage name; «@ISA = qw(parentclasses25);» members 1;package name; members
Rakuclass name «is parentclass «is parentclass ...26»» «does role «does role ...»» { members }role name «does role «does role ...»» { members }module name { members }
Rubyclass name« < parentclass» members endmodule name members end
Windows PowerShell
OCamlclass name «parameters» = object «(self)» «inherit parentclass «parameters» «inherit parentclass «parameters» ...27»» members endmodule name members
F#type name«(parameters)» «as this» = class «inherit parentclass«(parameters)» «as base»» members «interface interface with implementation «interface interface with implementation ...»» endtype name = interface members endnamespace name members
Smalltalk2829
JavaScript (ES6)class name «extends parentclass» { members }
Object Pascal (Delphi)

ClassName = Class «(ClassParent, Interfaces)»private// Private members(include Methods and Fields)public// Public membersprotected// Protected memberspublished// Published membersend;

package name; members
Scalaclass ConcreteClass(constructor params)extends ParentClasswith Trait1 with Trait2 with Trait2 {// members}trait TraitNameextends OtherTrait1with OtherTrait2 with OtherTrait3 {// members}package name
COBOLCLASS-ID. name« INHERITS« FROM» parentclasses».
    FACTORY« IMPLEMENTS interfaces».
    class-members
    END FACTORY.
    OBJECT« IMPLEMENTS interfaces».
    instance-members
    END OBJECT.

END CLASS name.

INTERFACE-ID. name« INHERITS« FROM» interfaces».
    members

END INTERFACE name.

Cobraclass name «inherits parentclass» «implements interfaces»Tab ↹ membersinterface name «inherits parentinterfaces»Tab ↹ membersnamespace nameTab ↹ members
ISLISP(defclass name (base-class) ((x :initform 0 :accessor get-x :initarg x)) (:abstractp nil))

Class members

Constructors and destructors

constructordestructorfinalizer30
ABAP Objectsmethods constructor «importing parameter = argument»method constructor. instructions endmethod.31
APL (Dyalog)∇ name:Implements Constructor «:Base «expr»»instructions∇∇ name:Implements Destructorinstructions∇
C++class(«parameters») «: initializers32» { instructions }~class() { instructions }
C#class(«parameters») { instructions }void Dispose(){ instructions }~class() { instructions }
Dthis(«parameters») { instructions }~this() { instructions }
eCclass() { instructions }~class() { instructions }
Javaclass(«parameters») { instructions }void finalize() { instructions }
Eiffel3334
Objective-C (Cocoa)- (id)init { instructions... return self; } or - (id)initWithFoo:parameter «bar:parameter ...» { instructions... return self; }- (void)dealloc { instructions }- (void)finalize { instructions }
Swiftinit(«parameters») { instructions }deinit { instructions }
Pythondef __init__(self«, parameters»): Tab ↹ instructionsdef __del__(self): Tab ↹ instructions
Visual Basic .NETSub New(«parameters») instructions End SubSub Dispose() instructions End SubOverrides Sub Finalize() instructions End Sub
XojoSub Constructor(«parameters») instructions End SubSub Destructor() instructions End Sub
PHPfunction __construct(«parameters») { instructions }function __destruct() { instructions }
Perlsub new { my ($class«, parameters») = @_; my $self = {}; instructions ... bless($self, $class); return $self; }sub DESTROY { my ($self) = @_; instructions }
Rakusubmethod BUILD { instructions } or «multi » method new(««$self: »parameters») { self.bless(*, field1 => value1, ...); ... instructions }submethod DESTROY { instructions }
Rubydef initialize«(parameters)» instructions end
Windows PowerShell
OCamlinitializer instructions35
F#do instructions or new(parameters) = expression36member this.Dispose() = instructionsoverride this.Finalize() = instructions
JavaScriptfunction name(«parameters») { instructions }37
JavaScript (ES6)constructor(«parameters») { instructions }
COBOL38
Cobracue init(parameters)Tab ↹ base.initTab ↹ instructionsdef disposeTab ↹ instructions
ISLISP(defmethod initialize-object ((instance <class-name>) initvalues)

Fields

publicprivateprotectedfriend
ABAP Objectspublic section.39 data field type type.private section.40 data field type type.protected section.41 data field type type.42
APL (Dyalog):Field Public field «← value»:Field «Private» field «← value»
C++public: type field;private: type field;protected: type field;43
C#public type field «= value»;private type field «= value»;protected type field «= value»;internal type field «= value»;
Dpackage type field «= value»;
Javaprotected type field «= value»;type field «= value»;
eCpublic type field;private type field;
Eiffelfeature field: TYPEfeature {NONE} field: TYPEfeature {current_class} field: TYPEfeature {FRIEND} field: TYPE
Objective-C@public type field;@private type field;@protected type field;@package type field;
Swift
Smalltalk44
Pythonself.field = value4546
Visual Basic .NETPublic field As type «= value»Private field As type «= value»Protected field As type «= value»Friend field As type «= value»
XojoPublic field As type «= value»Private field As type «= value»Protected field As type «= value»
PHPpublic $field «= value»;private $field «= value»;protected $field «= value»;
Perl$self->{field} = value;47
Rakuhas« type »$.field« is rw»has« type »$!field
Ruby@field = value48
Windows PowerShellAdd-Member «-MemberType »NoteProperty «-Name »Bar «-Value »value-InputObject variable
OCamlval «mutable» field = value
F#let «mutable» field = value
JavaScriptthis.field = value this["field"] = value49
COBOLlevel-number field clauses.50
Cobravar field «as type» «= value»var __field «as type» «= value»var _field «as type» «= value»
ISLISP(field :initform value :accessor accessor-name :initarg keyword)

Methods

basic/void methodvalue-returning method
ABAP Objectsmethods name «importing parameter = argument» «exporting parameter = argument» «changing parameter = argument» «returning value(parameter)»method name. instructions endmethod.5152
APL (Dyalog)∇ «left argument» name «right arguments»instructions∇∇ result ← «left argument» name «right arguments»instructions∇
C++53type foo(«parameters»);

The implementation of methods is usually provided in a separate source file, with the following syntax

type class::foo(«parameters») { instructions }54
void foo(«parameters») { instructions }type foo(«parameters») { instructions ... return value; }
C#
D
Java
eCvoid ««type of 'this'»::»foo(«parameters») { instructions }type ««type of this»::»foo(«parameters») { instructions ... return value; }
Eiffelfoo ( «parameters» ) do instructions endfoo ( «parameters» ): TYPE do instructions... Result := value end
Objective-C- (void)foo«:parameter «bar:parameter ...»» { instructions }- (type)foo«:parameter «bar:parameter ...»» { instructions... return value; }
Swiftfunc foo(«parameters») { instructions }func foo(«parameters») -> type { instructions... return value }
Pythondef foo(self«, parameters»): Tab ↹ instructionsdef foo(self«, parameters»): Tab ↹ instructions Tab ↹ return value
Visual Basic .NETSub Foo(«parameters») instructions End SubFunction Foo(«parameters») As type instructions ... Return value End Function
XojoSub Foo(«parameters») instructions End SubFunction Foo(«parameters») As type instructions ... Return value End Function
PHPfunction foo(«parameters»)«: void» { instructions }function foo(«parameters»)«: type» { instructions ... return value; }
Perlsub foo { my ($self«, parameters») = @_; instructions }sub foo { my ($self«, parameters») = @_; instructions ... return value; }
Raku«has »«multi »method foo(««$self: »parameters») { instructions }«has «type »»«multi »method foo(««$self: »parameters») { instructions ... return value; }
Rubydef foo«(parameters)» instructions enddef foo«(parameters)» instructions expression resulting in return value end or def foo«(parameters)» instructions return value end
Windows PowerShellAdd-Member «-MemberType» ScriptMethod «-Name» foo «-Value» { «param(parameters)» instructions } -InputObject variableAdd-Member «-MemberType» ScriptMethod «-Name» foo «-Value» { «param(parameters)» instructions ... return value } -InputObject variable
OCamlmethod foo «parameters» = expression
F#member this.foo(«parameters») = expression
JavaScriptthis.method = function(«parameters») {instructions} name«.prototype.method = function(«parameters») {instructions}55 this.method = function(«parameters») {instructions... return value;} name«.prototype.method = function(«parameters») {instructions... return value;}56
Javascript (ES6)foo(«parameters») {instructions}foo(«parameters») {instructions... return value;}
COBOLMETHOD-ID. foo.«DATA DIVISION.LINKAGE SECTION.parameter declarations»PROCEDURE DIVISION« USING parameters».
    instructions

END METHOD foo.

METHOD-ID. foo.DATA DIVISION.LINKAGE SECTION.«parameter declarations»result-var declarationPROCEDURE DIVISION« USING parameters» RETURNING result-var.
    instructions

END METHOD foo.

Cobradef foo(parameters)Tab ↹ instructionsdef foo(parameters) as typeTab ↹ instructionsTab ↹ return value
ISLISP(defgeneric method (arg1 arg2))(defmethod method ((arg1 <class1> arg2 <class2>) ...)

Properties

How to declare a property named "Bar"

Manually implemented

read-writeread-onlywrite-only
ABAP Objects
APL (Dyalog):Property Bar∇ result ← Getinstructions∇∇ Set argumentsinstructions∇:EndProperty Bar:Property Bar∇ result ← Getinstructions∇:EndProperty Bar:Property Bar∇ Set argumentsinstructions∇:EndProperty Bar
C++
C#type Bar { get { instructions ... return value; } set { instructions } }type Bar { get { instructions ... return value; } }type Bar { set { instructions } }
D@property type bar() { instructions ... return value; } @property type bar(type value) { instructions ... return value; }@property type bar() { instructions ... return value; }@property type bar(type value) { instructions ... return value; }
eCproperty type Bar { get { instructions ... return value; } set { instructions } }property type Bar { get { instructions ... return value; } }property type Bar { set { instructions } }
Java
Objective-C 2.0 (Cocoa)@property (readwrite) type bar; and then inside @implementation - (type)bar { instructions } - (void)setBar:(type)value { instructions }@property (readonly) type bar; and then inside @implementation - (type)bar { instructions }
Swiftvar bar : type { get { instructions } set«(newBar)» { instructions } }var bar : type { instructions }
Eiffelfeature -- Access x: TYPE assign set_x feature -- Settings set_x (a_x: like x) do instructions ensure x_set: verification end
Pythondef setBar(self, value): Tab ↹ instructionsdef getBar(self):Tab ↹ instructionsTab ↹ return valuebar = property(getBar, setBar)57def getBar(self): Tab ↹ instructionsTab ↹ return valuebar = property(getBar)def setBar(self, value): Tab ↹ instructionsbar = property(fset = setBar)
Visual Basic .NETProperty Bar() As typeGetinstructionsReturn valueEnd GetSet (ByVal Value As type)instructionsEnd SetEnd PropertyReadOnly Property Bar() As typeGetinstructionsReturn valueEnd GetEnd PropertyWriteOnly Property Bar() As typeSet (ByVal Value As type)instructionsEnd SetEnd Property
XojoComputedProperty Bar() As typeGetinstructionsReturn valueEnd GetSet (ByVal Value As type)instructionsEnd SetEnd ComputedPropertyComputedProperty Bar() As typeGetinstructionsReturn valueEnd GetEnd ComputedPropertyComputedProperty Bar() As typeSet (value As type)instructionsEnd SetEnd ComputedProperty
PHPfunction __get($property) { switch ($property) { case 'Bar' : instructions ... return value; } }function __set($property, $value) { switch ($property) { case 'Bar' : instructions } }function __get($property) { switch ($property) { case 'Bar' : instructions ... return value; } }function __set($property, $value) { switch ($property) { case 'Bar' : instructions } }
Perlsub Bar { my $self = shift; if (my $Bar = shift) { # setter $self->{Bar} = $Bar; return $self; } else { # getter return $self->{Bar}; }}sub Bar { my $self = shift; if (my $Bar = shift) { # read-only die "Bar is read-only\n"; } else { # getter return $self->{Bar}; }}sub Bar { my $self = shift; if (my $Bar = shift) { # setter $self->{Bar} = $Bar; return $self; } else { # write-only die "Bar is write-only\n"; }}
Raku
Rubydef bar instructions expression resulting in return value end def bar=(value) instructions enddef bar instructions expression resulting in return value enddef bar=(value) instructions end
Windows PowerShellAdd-Member «-MemberType »ScriptProperty «-Name »Bar «-Value »{ instructions ... return value } «-SecondValue »{ instructions } -InputObject variableAdd-Member «-MemberType »ScriptProperty «-Name »Bar «-Value »{ instructions ... return value} -InputObject variableAdd-Member «-MemberType »ScriptProperty «-Name »Bar -SecondValue { instructions } -InputObject variable
OCaml
F#member this.Bar with get() = expression and set(value) = expressionmember this.Bar = expressionmember this.Bar with set(value) = expression
JavaScript (ES6)get bar(«parameters») { instructions ... return value}set bar(«parameters») { instructions } get bar(«parameters») { instructions ... return value}set bar(«parameters») { instructions }
COBOLMETHOD-ID. GET PROPERTY bar.DATA DIVISION.LINKAGE SECTION.return-var declarationPROCEDURE DIVISION RETURNING return-var.
    instructions

END METHOD.METHOD-ID. SET PROPERTY bar.DATA DIVISION.LINKAGE SECTION.value-var declarationPROCEDURE DIVISION USING value-var.

    instructions

END METHOD.

METHOD-ID. GET PROPERTY bar.DATA DIVISION.LINKAGE SECTION.return-var declarationPROCEDURE DIVISION RETURNING return-var.
    instructions

END METHOD.

METHOD-ID. SET PROPERTY bar.DATA DIVISION.LINKAGE SECTION.value-var declarationPROCEDURE DIVISION USING value-var.
    instructions

END METHOD.

Cobrapro bar «as type»Tab ↹ getTab ↹Tab ↹ instructionsTab ↹Tab ↹ return valueTab ↹ setTab ↹Tab ↹ instructionsget bar «as type»Tab ↹ instructionsTab ↹ return valueset bar «as type»Tab ↹ instructions
ISLISP

Automatically implemented

read-writeread-onlywrite-only
ABAP Objects
C++
C#type Bar { get; set; }type Bar { get; private set; }type Bar { private get; set; }
D
Java
Objective-C 2.0 (Cocoa)@property (readwrite) type bar; and then inside @implementation @synthesize bar;@property (readonly) type bar; and then inside @implementation @synthesize bar;
Swiftvar bar : typelet bar : type
Eiffel
Python@propertydef bar(self):Tab ↹[email protected] bar(self, value):Tab ↹instructions@propertydef bar(self):Tab ↹instructionsbar = property()@bar.setterdef bar(self, value):Tab ↹instructions
Visual Basic .NETProperty Bar As type« = initial_value» (VB 10)
PHP
Perl58use base qw(Class::Accessor);__PACKAGE__->mk_accessors('Bar');use base qw(Class::Accessor);__PACKAGE__->mk_ro_accessors('Bar');use base qw(Class::Accessor);__PACKAGE__->mk_wo_accessors('Bar');
Raku
Rubyattr_accessor :barattr_reader :barattr_writer :bar
Windows PowerShell
OCaml
F#member val Bar = value with get, set
COBOLlevel-number bar clauses PROPERTY.level-number bar clauses PROPERTY «WITH» NO SET.level-number bar clauses PROPERTY «WITH» NO GET.
Cobrapro bar from var «as type»get bar from var «as type»set bar from var «as type»

Overloaded operators

Standard operators

unarybinaryfunction call
ABAP Objects
C++type operator symbol () { instructions }type operator symbol (type operand2) { instructions }type operator () («parameters») { instructions }
C#static type operator symbol(type operand) { instructions }static type operator symbol(type operand1, type operand2) { instructions }
Dtype opUnary(string s)() if (s == "symbol") { instructions }type opBinary(string s)(type operand2) if (s == "symbol") { instructions } type opBinaryRight(string s)(type operand1) if (s == "symbol") switch (s) { instructions }type opCall(«parameters») { instructions }
Java
Objective-C
Swiftfunc symbol(operand1 : type) -> returntype { instructions } (outside class)func symbol(operand1 : type1, operand2 : type2) -> returntype { instructions } (outside class)
Eiffel59op_name alias "symbol": TYPE do instructions endop_name alias "symbol" (operand: TYPE1): TYPE2 do instructions end
Pythondef __opname__(self): Tab ↹ instructions Tab ↹ return valuedef __opname__(self, operand2): Tab ↹ instructions Tab ↹ return valuedef __call__(self«, parameters»): Tab ↹ instructions Tab ↹ return value
Visual Basic .NETShared Operator symbol(operand As type) As type instructions End OperatorShared Operator symbol(operand1 As type, operand2 As type) As type instructions End Operator
XojoFunction Operator_name(operand As type) As type instructions End Function
PHP60function __invoke(«parameters») { instructions } (PHP 5.3+)
Perluse overload "symbol" => sub { my ($self) = @_; instructions };use overload "symbol" => sub { my ($self, $operand2, $operands_reversed) = @_; instructions };
Raku«our «type »»«multi »method prefix:<symbol> («$operand: ») { instructions ... return value; } or «our «type »»«multi »method postfix:<symbol> («$operand: ») { instructions ... return value; } or «our «type »»«multi »method circumfix:<symbol1 symbol2> («$operand: ») { instructions ... return value; }«our «type »»«multi »method infix:<symbol> («$operand1: » type operand2) { instructions ... return value; }«our «type »»«multi »method postcircumfix:<( )> («$self: » «parameters») { instructions }
Rubydef symbol instructions expression resulting in return value enddef symbol(operand2) instructions expression resulting in return value end
Windows PowerShell
OCaml
F#static member (symbol) operand = expressionstatic member (symbol) (operand1, operand2) = expression
COBOL
ISLISP

Indexers

read-writeread-onlywrite-only
ABAP Objects
APL (Dyalog):Property Numbered Default name∇ result ← Getinstructions∇∇ Set argumentsinstructions∇:EndProperty Bar:Property Numbered Default Bar∇ result ← Getinstructions∇:EndProperty Bar:Property Numbered Default Bar∇ Set argumentsinstructions∇:EndProperty Bar
C++type& operator[](type index) { instructions }type operator[](type index) { instructions }
C#type this[type index] { get{ instructions } set{ instructions } }type this[type index] { get{ instructions } }type this[type index] { set{ instructions } }
Dtype opIndex(type index) { instructions } type opIndexAssign(type value, type index) { instructions }type opIndex(type index) { instructions }type opIndexAssign(type value, type index) { instructions }
Java
Objective-C (recent Clang compiler)- (id)objectAtIndexedSubscript:(NSUInteger)index { instructions return value; } or- (id)objectForKeyedSubscript:(id)index { instructions return value; }- (void)setObject:(id)value atIndexedSubscript:(NSUInteger)index { instructions } or- (void)setObject:(id)value forKeyedSubscript:(id)index { instructions }
Swiftsubscript (index : type) -> returntype { get { instructions } set«(newIndex)» { instructions } }subscript (index : type) -> returntype { instructions }
Eiffel61bracket_name alias "[]" (index: TYPE): TYPE assign set_item do instructions end set_item (value: TYPE; index: TYPE): do instructions endbracket_name alias "[]" (index: TYPE): TYPE do instructions end
Pythondef __getitem__(self, index): Tab ↹ instructions Tab ↹ return value def __setitem__(self, index, value): Tab ↹ instructionsdef __getitem__(self, index): Tab ↹ instructions Tab ↹ return valuedef __setitem__(self, index, value): Tab ↹ instructions
Visual Basic .NETDefault Property Item(Index As type) As type Get instructions End Get Set(ByVal Value As type) instructions End Set End PropertyDefault ReadOnly Property Item(Index As type) As type Get instructions End Get End PropertyDefault WriteOnly Property Item(Index As type) As type Set(ByVal Value As type) instructions End Set End Property
PHP62
Perl63
Raku«our «type »»«multi »method postcircumfix:<[ ]> is rw («$self: » type $index) { instructions ... return value; } or «our «type »»«multi »method postcircumfix:<{ }> is rw («$self: » type $key) { instructions ... return value; }«our «type »»«multi »method postcircumfix:<[ ]>(«$self: » type $index) { instructions ... return value; } or «our «type »»«multi »method postcircumfix:<{ }> («$self: » type $key) { instructions ... return value; }
Rubydef [](index) instructions expression resulting in return value end def []=(index, value) instructions enddef [](index) instructions expression resulting in return value enddef []=(index, value) instructions end
Windows PowerShell
OCaml
F#member this.Item with get(index) = expression and set index value = expressionmember this.Item with get(index) = expressionmember this.Item with set index value = expression
COBOL
Cobrapro[index «as type»] as typeTab ↹ getTab ↹Tab ↹ instructionsTab ↹Tab ↹ return valueTab ↹ setTab ↹Tab ↹ instructionsget[index «as type»] as typeTab ↹ instructionsTab ↹ return valueset[index «as type»] as typeTab ↹ instructions

Type casts

downcastupcast
ABAP Objects
C++operator returntype() { instructions }
C#static explicit operator returntype(type operand) { instructions }static implicit operator returntype(type operand) { instructions }
DT opCast(T)() if (is(T == type)) { instructions }
eCproperty T { get { return «conversion code»; } }
Java
Objective-C
Eiffel64
Python
Visual Basic .NETShared Narrowing Operator CType(operand As type) As returntype instructions End Operator Shared Widening Operator CType(operand As type) As returntype instructions End Operator
PHP
Perl
Rakumulti method type«($self:)» is export { instructions }
Ruby
Windows PowerShell
OCaml
F#
COBOL

Member access

How to access members of an object x

object memberclass membernamespace member
methodfieldproperty
ABAP Objectsx->method(«parameters»).65x->fieldx=>field or x=>method(«parameters66»).
C++x.method(parameters) orptr->method(parameters)x.field orptr->fieldcls::memberns::member
Objective-C[x method«:parameter «bar:parameter ...»»]x->fieldx.property (2.0 only) or[x property][cls method«:parameter «bar:parameter ...»»]
Smalltalkx method«:parameter «bar:parameter ...»»cls method«:parameter «bar:parameter ...»»
Swiftx.method(parameters)x.propertycls.member
APL (Dyalog)left argument» x.method «right argument(s)»x.fieldx.propertycls.memberns.member
C#x.method(parameters)
Java
Dx.property
Python
Visual Basic .NET
Xojo
Windows PowerShell[cls]::member
F#cls.member
eCx.method«(parameters)»x.fieldx.propertycls::memberns::member
Eiffelx.method«(parameters)»x.field{cls}.member
Rubyx.propertycls.member
PHPx->method(parameters)x->fieldx->propertycls::memberns\member
Perlx->method«(parameters)»x->{field}cls->method«(parameters)»ns::member
Rakux.method«(parameters)» or x!method«(parameters)»x.field or x!fieldcls.method«(parameters)» or cls!method«(parameters)»ns::member
OCamlx#method «parameters»
JavaScriptx.method(parameters)x["method"](parameters)x.fieldx["field"]x.propertyx["property"]cls.membercls["member"]
COBOLINVOKE x "method" «USING parameters» «RETURNING result» orx::"method"«(«parameters»)»property OF xINVOKE cls "method" «USING parameters» «RETURNING result» orcls::"method"«(«parameters»)» orproperty OF cls
Cobrax.method«(parameters)»x.fieldx.propertycls.memberns.member

Member availability

Has member?Handler for missing member
MethodFieldMethodField
APL (Dyalog)3=x.⎕NC'method'2=x.⎕NC'method'
ABAP Objects
C++
Objective-C (Cocoa)[x respondsToSelector:@selector(method)]forwardInvocation:
Smalltalkx respondsTo: selectordoesNotUnderstand:
C#(using reflection)
eC
Java
DopDispatch()
Eiffel
Pythonhasattr(x, "method") and callable(x.method)hasattr(x, "field")__getattr__()
Visual Basic .NET(using reflection)
Xojo(using Introspection)
Windows PowerShell(using reflection)
F#(using reflection)
Rubyx.respond_to?(:method)method_missing()
PHPmethod_exists(x, "method")property_exists(x, "field")__call()__get() / __set()
Perlx->can("method")exists x->{field}AUTOLOAD
Rakux.can("method")x.field.definedAUTOLOAD
OCaml
JavaScripttypeof x.method === "function"field in x
COBOL

Special variables

current objectcurrent object's parent objectnull referenceCurrent Context of Execution
SmalltalkselfsupernilthisContext
ABAP Objectsmesuperinitial
APL (Dyalog)⎕THIS⎕BASE⎕NULL
C++*this67NULL, nullptr
C#thisbase68null
Javasuper69
D
JavaScriptsuper70 (ECMAScript 6)null, undefined71
eCthisnull
Objective-Cselfsuper72nil
Swiftselfsuper73nil74
Pythonself75super(current_class_name, self)76super() (3.x only)None
Visual Basic .NETMeMyBaseNothing
XojoMe / SelfParentNil
EiffelCurrentPrecursor «{superclass}» «(args)»7778Void
PHP$thisparent79null
Perl$self80$self->SUPER81undef
RakuselfSUPERNil
Rubyselfsuper«(args)»82nilbinding
Windows PowerShell$this$NULL
OCamlself83super8485
F#thisbase86null
COBOLSELFSUPERNULL
Cobrathisbasenil

Special methods

String representationObject copyValue equalityObject comparisonHash codeObject ID
Human-readableSource-compatible
ABAP Objects
APL (Dyalog)⍕x⎕SRC x⎕NS xx = y
C++x == y87pointer to object can be converted into an integer ID
C#x.ToString()x.Clone()x.Equals(y)x.CompareTo(y)x.GetHashCode()System.Runtime.CompilerServices.RuntimeHelpers.GetHashCode(x)
Javax.toString()x.clone()88x.equals(y)x.compareTo(y)89x.hashCode()System.identityHashCode(x)
JavaScriptx.toString()
Dx.toString() or std.conv.to!string(x)x.stringofx == y or x.opEquals(y)x.opCmp(y)x.toHash()
eCx.OnGetString(tempString, null, null) or PrintString(x)y.OnCopy(x)x.OnCompare(y)object handle can be converted into an integer ID
Objective-C (Cocoa)x.descriptionx.debugDescription[x copy]90[x isEqual:y][x compare:y]91x.hashpointer to object can be converted into an integer ID
Swiftx.description92x.debugDescription93x == y94x < y95x.hashValue96reflect(x).objectIdentifier!.uintValue()
Smalltalkx displayStringx printStringx copyx = yx hashx identityHash
Pythonstr(x)97repr(x)98copy.copy(x)99x == y100cmp(x, y)101hash(x)102id(x)
Visual Basic .NETx.ToString()x.Clone()x.Equals(y)x.CompareTo(y)x.GetHashCode()
Eiffelx.outx.twinx.is_equal(y)When x is COMPARABLE, one can simply do x < yWhen x is HASHABLE, one can use x.hash_codeWhen x is IDENTIFIED, one can use x.object_id
PHP$x->__toString()clone x103x == yspl_object_hash(x)
Perl"$x"104Data::Dumper->Dump([$x],['x'])105Storable::dclone($x)106Scalar::Util::refaddr( $x )107
Raku~x108x.perlx.clonex eqv yx cmp yx.WHICH
Rubyx.to_sx.inspectx.dup or x.clonex == y or x.eql?(y)x <=> yx.hashx.object_id
Windows PowerShellx.ToString()x.Clone()x.Equals(y)x.CompareTo(y)x.GetHashCode()
OCamlOo.copy xx = yHashtbl.hash xOo.id x
F#string x or x.ToString() or sprintf "%O" xsprintf "%A" xx.Clone()x = y or x.Equals(y)compare x y or x.CompareTo(y)hash x or x.GetHashCode()
COBOL

Type manipulation

Get object typeIs instance of (includes subtypes)UpcastingDowncasting
Runtime checkNo check
ABAP Objects109=?=
C++typeid(x)dynamic_cast<type *>(&x) != nullptr110dynamic_cast<type*>(ptr)(type*) ptr or static_cast<type*>(ptr)
C#x.GetType()x is type(type) x or x as type
Dtypeid(x)cast(type) x
Delphix is typex as type
eCx._classeClass_IsDerived(x._class, type)(type) x
Javax.getClass()x instanceof class(type) x
Objective-C (Cocoa)[x class]111[x isKindOfClass:[class class]](type*) x
Swiftx.dynamicTypex is typex as! type x as? type
JavaScriptx.constructor (If not rewritten.)x instanceof class112
Visual Basic .NETx.GetType()TypeOf x Is type113CType(x, type) or TryCast(x, type)
XojoIntrospection.GetType(x)x IsA typeCType(x, type)
Eiffelx.generating_typeattached {TYPE} xattached {TYPE} x as down_x
Pythontype(x)isinstance(x, type)114
PHPget_class(x)x instanceof class
Perlref(x)x->isa("class")
Rakux.WHATx.isa(class)115type(x) or x.type
Rubyx.classx.instance_of?(type) or x.kind_of?(type)116
Smalltalkx classx isKindOf: class
Windows PowerShellx.GetType()x -is [type]117[type]x or x -as [type]
OCaml118(x :> type)
F#x.GetType()x :? type(x :?> type)
COBOLx AS type119

Namespace management

Import namespaceImport item
qualifiedunqualified
ABAP Objects
C++using namespace ns;using ns::item ;
C#using ns;using item = ns.item;
Dimport ns;import ns : item;
Javaimport ns.*;import ns.item;
Objective-C
Visual Basic .NETImports ns
Eiffel
Pythonimport nsfrom ns import *from ns import item
PHPuse ns;use ns\item;
Perluse ns;use ns qw(item);
Raku
Ruby
Windows PowerShell
OCamlopen ns
F#
COBOL

Contracts

PreconditionPostconditionCheckInvariantLoop
ABAP Objects
C++
C#Spec#: type foo( «parameters» )    requires expression {     body }Spec#: type foo( «parameters» )    ensures expression {     body }
Java
Objective-C
Visual Basic .NET
Df in { asserts } body{ instructions }f out (result) { asserts } body{ instructions }assert(expression)invariant() { expression }
Eiffelf require tag: expression do endf do ensure tag: expression endf do check tag: expression end endclass X invariant tag: expression endfrom instructions invariant tag: expression until expr loop instructions variant tag: expression end
Python
PHP
Perl
RakuPRE { condition }POST { condition }
Ruby
Windows PowerShell
OCaml
F#
COBOL

See also

Notes

References

  1. parameter = argument may be repeated if the constructor has several parameters

  2. SAP reserved to himself the use of destruction /wiki/SAP_R/3

  3. This language uses garbage collection to release unused memory. /wiki/Garbage_collection_(computer_science)

  4. This syntax creates an object value with automatic storage duration

  5. This syntax creates an object with dynamic storage duration and returns a pointer to it

  6. This language uses garbage collection to release unused memory. /wiki/Garbage_collection_(computer_science)

  7. This language uses garbage collection to release unused memory. /wiki/Garbage_collection_(computer_science)

  8. This language uses garbage collection to release unused memory. /wiki/Garbage_collection_(computer_science)

  9. This language uses garbage collection to release unused memory. /wiki/Garbage_collection_(computer_science)

  10. This language uses garbage collection to release unused memory. /wiki/Garbage_collection_(computer_science)

  11. This language uses garbage collection to release unused memory. /wiki/Garbage_collection_(computer_science)

  12. This language uses garbage collection to release unused memory. /wiki/Garbage_collection_(computer_science)

  13. OCaml objects can be created directly without going through a class.

  14. This language uses garbage collection to release unused memory. /wiki/Garbage_collection_(computer_science)

  15. This language uses garbage collection to release unused memory. /wiki/Garbage_collection_(computer_science)

  16. This language uses garbage collection to release unused memory. /wiki/Garbage_collection_(computer_science)

  17. This language uses garbage collection to release unused memory. /wiki/Garbage_collection_(computer_science)

  18. This language supports multiple inheritance. A class can have more than one parent class /wiki/Multiple_inheritance

  19. Not providing a parent class makes the class a root class. In practice, this is almost never done. One should generally use the conventional base class of the framework one is using, which is NSObject for Cocoa and GNUstep, or Object otherwise.

  20. Usually the @interface portion is placed into a header file, and the @interface portion is placed into a separate source code file. /wiki/Header_file

  21. Prefixes to class and protocol names conventionally used as a kind of namespace

  22. This language supports multiple inheritance. A class can have more than one parent class /wiki/Multiple_inheritance

  23. In Python interfaces are classes which methods have pass as their bodies

  24. This language supports multiple inheritance. A class can have more than one parent class /wiki/Multiple_inheritance

  25. This language supports multiple inheritance. A class can have more than one parent class /wiki/Multiple_inheritance

  26. This language supports multiple inheritance. A class can have more than one parent class /wiki/Multiple_inheritance

  27. This language supports multiple inheritance. A class can have more than one parent class /wiki/Multiple_inheritance

  28. The class is an Object. Just send a message to the superclass (st-80) or the destination namespace (Visualworks).

  29. The namespace is an Object.Just send a message to the parent namespace.

  30. A finalizer is called by the garbage collector when an object is about to be garbage-collected. There is no guarantee on when it will be called or if it will be called at all. /wiki/Finalizer

  31. In ABAP, the constructor is to be defined like a method (see comments about method) with the following restrictions: the method name must be "constructor", and only "importing" parameters can be defined

  32. An optional comma-separated list of initializers for member objects and parent classes goes here. The syntax for initializing member objects is "member_name(parameters)" This works even for primitive members, in which case one parameter is specified and that value is copied into the member. The syntax for initializing parent classes is "class_name(parameters)". If an initializer is not specified for a member or parent class, then the default constructor is used. /wiki/Default_constructor

  33. Any Eiffel procedure can be used as a creation procedure, aka constructors. See Eiffel paragraph at Constructor (computer science). /wiki/Constructor_(computer_science)#Eiffel

  34. Implementing {DISPOSABLE}.dispose ensures that dispose will be called when object is garbage collected.

  35. This "initializer" construct is rarely used. Fields in OCaml are usually initialized directly in their declaration. Only when additional imperative operations are needed is "initializer" used. The "parameters to the constructor" in other languages are instead specified as the parameters to the class in OCaml. See the class declaration syntax for more details.

  36. This syntax is usually used to overload constructors /wiki/Method_overloading

  37. In JavaScript, constructor is an object.

  38. Constructors can be emulated with a factory method returning a class instance.

  39. Scope identifier must appear once in the file declaration, all variable declarations after this scope identifier have his scope, until another scope identifier or the end of class declaration is reached

  40. Scope identifier must appear once in the file declaration, all variable declarations after this scope identifier have his scope, until another scope identifier or the end of class declaration is reached

  41. Scope identifier must appear once in the file declaration, all variable declarations after this scope identifier have his scope, until another scope identifier or the end of class declaration is reached

  42. In ABAP, specific fields or methods are not declared as accessible by outside things. Rather, outside classes are declared as friends to have access to the class's fields or methods.

  43. In C++, specific fields are not declared as accessible by outside things. Rather, outside functions and classes are declared as friends to have access to the class's fields. See friend function and friend class for more details. /wiki/Friend_function

  44. Just send a message to the class class addInstVarName: field. class removeInstVarName: field.

  45. Just assign a value to it in a method

  46. Python doesn't have private fields - all fields are publicly accessible at all times. A community convention exists to prefix implementation details with one underscore, but this is unenforced by the language.

  47. Just assign a value to it in a method

  48. Just assign a value to it in a method

  49. Just assign a value to it in a method

  50. All class data is 'private' because the COBOL standard does not specify any way to access it.

  51. The declaration and implementation of methods in ABAP are separate. methods statement is to be used inside the class definition. method (without "s") is to be used inside the class implementation. parameter = argument can be repeated if there are several parameters.

  52. In ABAP, the return parameter name is explicitly defined in the method signature within the class definition

  53. In C++, declaring and implementing methods is usually separate. Methods are declared in the class definition (which is usually included in a header file) using the syntax /wiki/Header_file

  54. Although the body of a method can be included with the declaration inside the class definition, as shown in the table here, this is generally bad practice. Because the class definition must be included with every source file which uses the fields or methods of the class, having code in the class definition causes the method code to be compiled with every source file, increasing the size of the code. Yet, in some circumstances, it is useful to include the body of a method with the declaration. One reason is that the compiler will try to inline methods that are included in the class declaration; so if a very short one-line method occurs, it may make it faster to allow a compiler to inline it, by including the body along with the declaration. Also, if a template class or method occurs, then all the code must be included with the declaration, because only with the code can the template be instantiated. /wiki/Inline_function

  55. Just assign a function to it in a method

  56. Just assign a function to it in a method

  57. Alternative implementation: def bar(): doc = "The bar property." def fget(self): return self._bar def fset(self, value): self._bar = value return locals() bar = property(**bar())

  58. these examples need the Class::Accessor module installed https://metacpan.org/module/Class::Accessor

  59. Although Eiffel does not support overloading of operators, it can define operators

  60. PHP does not support operator overloading natively, but support can be added using the "operator" PECL package. /wiki/Operator_overloading

  61. Although Eiffel does not support overloading of operators, it can define operators

  62. The class must implement the ArrayAccess interface. http://www.php.net/manual/en/class.arrayaccess.php

  63. The class must overload '@{}' (array dereference) or subclass one of Tie::Array or Tie::StdArray to hook array operations

  64. Although Eiffel does not support overloading of operators, it can define operators

  65. In ABAP, arguments must be passed using this syntax: x->method(«exporting parameter = argument» «importing parameter = argument» «changing parameter = argument» «returning value(parameter)» parameter = argument can be repeated if there are several parameters

  66. In ABAP, arguments must be passed using this syntax: x->method(«exporting parameter = argument» «importing parameter = argument» «changing parameter = argument» «returning value(parameter)» parameter = argument can be repeated if there are several parameters

  67. C++ doesn't have a "super" keyword, because multiple inheritance is possible, and so it may be ambiguous which base class is referenced. Instead, the BaseClassName::member syntax can be used to access an overridden member in the specified base class. Microsoft Visual C++ provides a non-standard keyword "__super" for this purpose; but this is unsupported in other compilers.[1] http://msdn.microsoft.com/en-us/library/94dw1w7x.aspx

  68. The keyword here is not a value, and it can only be used to access a method of the superclass.

  69. The keyword here is not a value, and it can only be used to access a method of the superclass.

  70. The keyword here is not a value, and it can only be used to access a method of the superclass.

  71. But be afraid, they have not the same value.

  72. The keyword here is not a value, and it can only be used to access a method of the superclass.

  73. The keyword here is not a value, and it can only be used to access a method of the superclass.

  74. only for Optional types

  75. In this language, instance methods are passed the current object as the first parameter, which is conventionally named "self", but this is not required to be the case.

  76. This language supports multiple inheritance. A class can have more than one parent class /wiki/Multiple_inheritance

  77. The keyword here is not a value, and it can only be used to access a method of the superclass.

  78. "Precursor" in Eiffel is actually a call to the method of the same name in the superclass. So Precursor(args) is equivalent to "super.currentMethodName(args)" in Java. There is no way of calling a method of different name in the superclass.

  79. The keyword here is not a value, and it can only be used to access a method of the superclass.

  80. In this language, instance methods are passed the current object as the first parameter, which is conventionally named "self", but this is not required to be the case.

  81. The keyword here is not a value, and it can only be used to access a method of the superclass.

  82. "super" in Ruby, unlike in other languages, is actually a call to the method of the same name in the superclass. So super(args) in Ruby is equivalent to "super.currentMethodName(args)" in Java. There is no way of calling a method of different name in the superclass.

  83. In OCaml, an object declaration can optionally start with a parameter which will be associated with the current object. This parameter is conventionally named "self", but this is not required to be the case. It is good practice to put a parameter there so that one can call one's own methods.

  84. In OCaml, an inheritance declaration ("inherit") can optionally be associated with a value, with the syntax "inherit parent_class «parameters» as super". Here "super" is the name given to the variable associated with this parent object. It can be named differently.

  85. However, if the ability to have an "optional" value in OCaml is needed, then wrap the value inside an option type, which values are None and Some x, which could be used to represent "null reference" and "non-null reference to an object" as in other languages.

  86. The keyword here is not a value, and it can only be used to access a method of the superclass.

  87. assuming that "x" and "y" are the objects (and not pointers). Can be customized by overloading the object's == operator

  88. Only accessible from within the class, since the clone() method inherited from Object is protected, unless the class overrides the method and makes it public. If using the clone() inherited from Object, the class must implement the Cloneable interface to allow cloning.

  89. The class should implement the interface Comparable for this method to be standardized.

  90. Implemented by the object's copyWithZone: method

  91. compare: is the conventional name for the comparison method in Foundation classes. However, no formal protocol exists

  92. Only if object conforms to the Printable protocol

  93. Only if object conforms to the DebugPrintable protocol

  94. Only if object conforms to the Equatable protocol

  95. Only if object conforms to the Comparable protocol

  96. Only if object conforms to the hashValue protocol

  97. Can be customized by the object's __str__() method

  98. Can be customized by the object's __repr__() method

  99. Can be customized by the object's __copy__() method

  100. Can be customized by the object's __eq__() method

  101. Only in Python 2.x and before (removed in Python 3.0). Can be customized by the object's __cmp__() method

  102. Can be customized by the object's __hash__() method. Not all types are hashable (mutable types are usually not hashable)

  103. Can be customized by the object's __clone() method

  104. Can be customized by overloading the object's string conversion operator

  105. This example requires useing Data::Dumper

  106. This example requires useing Storable

  107. This example requires useing Scalar::Util

  108. Can be customized by overloading the object's string conversion operator

  109. Run-time type information in ABAP can be gathered by using different description Classes like CL_ABAP_CLASSDESCR.

  110. Upcasting is implicit in this language. A subtype instance can be used where a supertype is needed.

  111. Only for non-class objects. If x is a class object, [x class] returns only x. The runtime method object_getClass(x) will return the class of x for all objects.

  112. This language is dynamically typed. Casting between types is unneeded.

  113. Upcasting is implicit in this language. A subtype instance can be used where a supertype is needed.

  114. This language is dynamically typed. Casting between types is unneeded.

  115. Upcasting is implicit in this language. A subtype instance can be used where a supertype is needed.

  116. This language is dynamically typed. Casting between types is unneeded.

  117. Upcasting is implicit in this language. A subtype instance can be used where a supertype is needed.

  118. This language doesn't give run-time type information. It is unneeded because it is statically typed and downcasting is impossible.

  119. Upcasting is implicit in this language. A subtype instance can be used where a supertype is needed.