Английская Википедия:Comparison of programming languages (object-oriented programming)

Материал из Онлайн справочника
Перейти к навигацииПерейти к поиску

Шаблон:Cleanup Шаблон:ProgLangCompare 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

construction destruction
ABAP Objects data variable type ref to class .
create object variable «exporting parameter = argument».
[1]
[2][3]
APL (Dyalog) variable←⎕NEW class «parameters» ⎕EX 'variable'
C++ class variable«(parameters)»;[4] or
class *variable = new class«(parameters)»;[5]
delete pointer;
C# class variable = new class(parameters); variable.Dispose();[3]
Java [3]
D destroy(variable);
eC class «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];
Swift let variable = class(parameters)
Python variable = class(parameters) del variable[3] (Normally not needed)
Visual Basic .NET Dim variable As New class(parameters) variable.Dispose()[3]
Xojo Dim variable As New class(parameters) variable = Nil
Eiffel create variable or
create «{TYPE}» variable.make_foo «(parameters)» or
variable := create {TYPE} or
variable := create {TYPE}.make_foo «(parameters)»
[3]
PHP $variable = new class«(parameters)»; unset($variable);[3]
Perl 5 «my »$variable = class->new«(parameters)»; undef($variable);
Raku «my »$variable = class.new«(parameters)»; $variable.undefine;
Ruby variable = class.new«(parameters)» [3]
Windows PowerShell $variable = New-Object «-TypeName» class ««-ArgumentList» parameters» Remove-Variable «-Name» variable
OCaml let variable = new class «parameters» or
let variable = object members end[6]
[3]
F# let variable = «new »class(«parameters»)
Smalltalk The 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.
JavaScript var variable = new class«(parameters)» or
var variable = { «key1: value1«, key2: value2 ...»»}
[3]
Шаблон:Nowrap (Delphi) ClassVar := ClassType.ConstructorName(parameters); ClassVar.Free;
Scala
val obj = new Object // no parameters
val obj = new Object(arg0, arg1, arg2...)
val obj = Object(arg0, arg1, arg2...) // case class
val obj = new Object(arg0, arg1, param1 = value1, ...) // named parameters
[3]
COBOL INVOKE class "NEW" RETURNING variable or
MOVE class::"NEW" TO variable
Cobra variable «as class» = class(parameters) variable.dispose
ISLISP (setq variable (create (class <some-class> [:field-1 value-1 [:field-2 value-2] ..]))) [3]

Class declaration

class protocol namespace
ABAP Objects class name definition «inheriting from parentclass». «interfaces: interfaces.» method_and_field_declarations endclass.
class name implementation. method_implementations endclass.
interface name. members endinterface. Шаблон:N/a
APL (Dyalog) :Class name «:parentclass» «,interfaces»
members
:EndClass
:Interface name
members
:EndInterface
:Namespace name
members
:EndNamespace
C++ class name« : public parentclasses[7]» { members }; namespace name { members }
C# class name« : «parentclass»«, interfaces»» { members } interface name« : parentinterfaces» { members }
D module name;
members
eC class name« : base class» { «default member values assignments» «members» } namespace name;
Java class name« extends parentclass»« implements interfaces» { members } interface name« extends parentinterfaces» { members } package name; members
PHP namespace name; members
Objective-C @interface name« : parentclass»[8]«< protocols >» { instance_fields } method_and_property_declarations @end
@implementation
name method_implementations @end
[9]
@protocol name«< parentprotocols >» members @end Шаблон:N/a
Swift class name« : «parentclass»«, protocols»» { members } protocol name« : parentprotocols» { members }
Python class name«(parentclasses[7])»:
Шаблон:Keypress
members
[10] __all__ = [ member1,member2,... ]
Visual Basic .NET Class name« Inherits parentclass»« Implements interfaces»
members
End Class
Interface name« Inherits parentinterfaces»
members
End Interface
Namespace name
members
End Namespace
Xojo Class name« Inherits parentclass»« Implements interfaces»
members
End Class
Interface name« Inherits parentinterfaces»
members
End Interface
Module name
members
End Module
Eiffel class name« inherit parentclasses[7]»
members
end
colspan=2 Шаблон:N/a
Perl package name; «@ISA = qw(parentclasses[7]);» members 1; package name; members
Raku class name «is parentclass «is parentclass ...[7]»» «does role «does role ...»» { members } role name «does role «does role ...»» { members } module name { members }
Ruby class name« < parentclass»
members
end
module name
members
end
Windows PowerShell colspan=3 Шаблон:N/a
OCaml class name «parameters» = object «(self)» «inherit parentclass «parameters» «inherit parentclass «parameters» ...[7]»» members end module name
members
F# type name«(parameters)» «as this» = class «inherit parentclass«(parameters)» «as base»» members «interface interface with implementation «interface interface with implementation ...»» end type name = interface members end namespace name
members
Smalltalk [11] [12]
JavaScript (ES6) class name «extends parentclass» { members }
Object Pascal (Delphi) <poem>ClassName = Class «(ClassParent, Interfaces)»

private // Private members(include Methods and Fields) public // Public members protected // Protected members published // Published members end;</poem>

package name; members
Scala
class ConcreteClass(constructor params)
extends ParentClass
with Trait1 with Trait2 with Trait2 {
// members
}
trait TraitName
extends OtherTrait1
with OtherTrait2 with OtherTrait3 {
// members
}
package name
COBOL CLASS-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.

Шаблон:N/a
Cobra class name «inherits parentclass» «implements interfaces»
Шаблон:Keypress members
interface name «inherits parentinterfaces»
Шаблон:Keypress members
namespace name
Шаблон:Keypress members
ISLISP (defclass name (base-class) ((x :initform 0 :accessor get-x :initarg x)) (:abstractp nil))

Class members

Constructors and destructors

constructor destructor finalizer[13]
ABAP Objects methods constructor «importing parameter = argument»
method constructor. instructions endmethod.
[14]
colspan=2 Шаблон:N/a
APL (Dyalog) name
:Implements Constructor «:Base «expr»»
instructions
name
:Implements Destructor
instructions
C++ class(«parameters») «: initializers[15]» { instructions } ~class() { instructions }
C# class(«parameters») { instructions } void Dispose(){ instructions } ~class() { instructions }
D this(«parameters») { instructions } ~this() { instructions }
eC class() { instructions } ~class() { instructions }
Java class(«parameters») { instructions } void finalize() { instructions }
Eiffel [16] [17]
Objective-C (Cocoa) - (id)init { instructions... return self; } or
- (id)initWithFoo:parameter «bar:parameter ...» { instructions... return self; }
- (void)dealloc { instructions } - (void)finalize { instructions }
Swift init(«parameters») { instructions } deinit { instructions }
Python def __init__(self«, parameters»):
Шаблон:Keypress instructions
def __del__(self):
Шаблон:Keypress instructions
Visual Basic .NET Sub New(«parameters»)
instructions
End Sub
Sub Dispose()
instructions
End Sub
Overrides Sub Finalize()
instructions
End Sub
Xojo Sub Constructor(«parameters»)
instructions
End Sub
Sub Destructor()
instructions
End Sub
PHP function __construct(«parameters») { instructions } function __destruct() { instructions }
Perl sub new { my ($class«, parameters») = @_; my $self = {}; instructions ... bless($self, $class); return $self; } sub DESTROY { my ($self) = @_; instructions }
Raku submethod BUILD { instructions } or
«multi » method new(««$self: »parameters») { self.bless(*, field1 => value1, ...); ... instructions }
submethod DESTROY { instructions }
Ruby def initialize«(parameters)»
instructions
end
colspan=2 Шаблон:N/a
Windows PowerShell colspan=3 Шаблон:N/a
OCaml initializer instructions[18] colspan=2 Шаблон:N/a
F# do instructions or
new(parameters) = expression
[19]
member this.Dispose() = instructions override this.Finalize() = instructions
JavaScript function name(«parameters») { instructions }[20] colspan=2 Шаблон:N/a
JavaScript (ES6) constructor(«parameters») { instructions }
COBOL Шаблон:N/a[21] colspan=2 Шаблон:N/a
Cobra cue init(parameters)
Шаблон:Keypress base.init
Шаблон:Keypress instructions
def dispose
Шаблон:Keypress instructions
ISLISP (defmethod initialize-object ((instance <class-name>) initvalues)

Fields

public private protected friend
ABAP Objects public section.[22] data field type type. private section.[22] data field type type. protected section.[22] data field type type. [23]
APL (Dyalog) :Field Public field « value» :Field «Private» field « value»
C++ public: type field; private: type field; protected: type field; [24]
C# public type field «= value»; private type field «= value»; protected type field «= value»; internal type field «= value»;
D package type field «= value»;
Java protected type field «= value»; type field «= value»;
eC public type field; private type field;
Eiffel feature
field: TYPE
feature {NONE}
field: TYPE
feature {current_class}
field: TYPE
feature {FRIEND}
field: TYPE
Objective-C @public type field; @private type field; @protected type field; @package type field;
Swift colspan=4 Шаблон:N/a
Smalltalk colspan=2 Шаблон:N/a [25] Шаблон:N/a
Python self.field = value[26] Шаблон:N/a[27] colspan=2 Шаблон:N/a
Visual Basic .NET Public field As type «= value» Private field As type «= value» Protected field As type «= value» Friend field As type «= value»
Xojo Public field As type «= value» Private field As type «= value» Protected field As type «= value» Шаблон:N/a
PHP public $field «= value»; private $field «= value»; protected $field «= value»;
Perl $self->{field} = value;[26] colspan=3 Шаблон:N/a
Raku has« type »$.field« is rw» has« type »$!field colspan=2 Шаблон:N/a
Ruby colspan=2 Шаблон:N/a @field = value[26]
Windows PowerShell Add-Member
«-MemberType »NoteProperty
«-Name »Bar «-Value »value
-InputObject variable
colspan=3 Шаблон:N/a
OCaml colspan=2 Шаблон:N/a val «mutable» field = value rowspan=2 Шаблон:N/a
F# Шаблон:N/a let «mutable» field = value Шаблон:N/a
JavaScript this.field = value
this["field"] = value
[26]
COBOL Шаблон:N/a level-number field clauses.[28] Шаблон:N/a Шаблон:N/a
Cobra var 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 method value-returning method
ABAP Objects methods name «importing parameter = argument» «exporting parameter = argument» «changing parameter = argument» «returning value(parameter)»
method name. instructions endmethod.
[29]
[30]
APL (Dyalog) «left argument» name «right arguments»
instructions
result «left argument» name «right arguments»
instructions
C++[31]
type foo(«parameters»);

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

type class::foo(«parameters») { instructions }[32]
void foo(«parameters») { instructions } type foo(«parameters») { instructions ... return value; }
C#
D
Java
eC void ««type of 'this'»::»foo(«parameters») { instructions } type ««type of this»::»foo(«parameters») { instructions ... return value; }
Eiffel foo ( «parameters» )
do
instructions
end
foo ( «parameters» ): TYPE
do
instructions...
Result := value
end
Objective-C - (void)foo«:parameter «bar:parameter ...»» { instructions } - (type)foo«:parameter «bar:parameter ...»» { instructions... return value; }
Swift func foo(«parameters») { instructions } func foo(«parameters») -> type { instructions... return value }
Python def foo(self«, parameters»):
Шаблон:Keypress
instructions
def foo(self«, parameters»):
Шаблон:Keypress
instructions
Шаблон:Keypress return
value
Visual Basic .NET Sub Foo(«parameters»)
instructions
End Sub
Function Foo(«parameters») As type
instructions
...
Return value
End Function
Xojo Sub Foo(«parameters»)
instructions
End Sub
Function Foo(«parameters») As type
instructions
...
Return value
End Function
PHP function foo(«parameters»)«: void» { instructions } function foo(«parameters»)«: type» { instructions ... return value; }
Perl sub 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; }
Ruby def foo«(parameters)»
instructions
end
def foo«(parameters)»
instructions
expression resulting in return value
end
or
def foo«(parameters
instructions
return value
end
Windows PowerShell Add-Member «-MemberType» ScriptMethod «-Name» foo «-Value» { «param(parameters)» instructions } -InputObject variable Add-Member «-MemberType» ScriptMethod «-Name» foo «-Value» { «param(parameters)» instructions ... return value } -InputObject variable
OCaml rowspan=2 Шаблон:N/a method foo «parameters» = expression
F# member this.foo(«parameters») = expression
JavaScript this.method = function(«parameters») {instructions}
name«.prototype.method = function(«parameters») {instructions}
[33]
this.method = function(«parameters») {instructions... return value;}
name«.prototype.method = function(«parameters») {instructions... return value;}
[33]
Javascript (ES6) foo(«parameters») {instructions} foo(«parameters») {instructions... return value;}
COBOL METHOD-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 declaration
PROCEDURE DIVISION« USING parameters» RETURNING result-var.
    instructions

END METHOD foo.

Cobra def foo(parameters)
Шаблон:Keypress instructions
def foo(parameters) as type
Шаблон:Keypress instructions
Шаблон:Keypress return value
ISLISP (defgeneric method (arg1 arg2))
(defmethod method ((arg1 <class1> arg2 <class2>) ...)

Properties

How to declare a property named "Bar"

Manually implemented

read-write read-only write-only
ABAP Objects colspan=3 Шаблон:N/a
APL (Dyalog) :Property Bar
result ← Get
instructions

∇ Set arguments
instructions

:EndProperty Bar
:Property Bar
result ← Get
instructions

:EndProperty Bar
:Property Bar
∇ Set arguments
instructions

:EndProperty Bar
C++ colspan=3 Шаблон:N/a
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; }
eC property type Bar {
get {
instructions ... return value; }
set {
instructions } }
property type Bar { get { instructions ... return value; } } property type Bar { set { instructions } }
Java colspan=3 Шаблон:N/a
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 }
Шаблон:N/a
Swift var bar : type { get { instructions } set«(newBar)» { instructions } } var bar : type { instructions } Шаблон:N/a
Eiffel feature -- Access
x: TYPE assign set_x
feature -- Settings
set_x (a_x: like x) do instructions ensure x_set: verification end
Python def setBar(self, value):
Шаблон:Keypress instructions
def
getBar(self):
Шаблон:Keypress
instructions
Шаблон:Keypress return value
bar = property(getBar, setBar)
[34]
def getBar(self):
Шаблон:Keypress instructions
Шаблон:Keypress return value
bar = property(getBar)
def setBar(self, value):
Шаблон:Keypress instructions
bar = property(fset = setBar)
Visual Basic .NET Property Bar() As type
Get
instructions
Return value
End Get
Set (ByVal
Value As type)
instructions
End Set
End Property
ReadOnly Property Bar() As type
Get
instructions
Return value
End Get
End Property
WriteOnly Property Bar() As type
Set (ByVal Value As type)
instructions
End Set
End Property
Xojo ComputedProperty Bar() As type
Get
instructions
Return value
End Get
Set (ByVal
Value As type)
instructions
End Set
End ComputedProperty
ComputedProperty Bar() As type
Get
instructions
Return value
End Get
End ComputedProperty
ComputedProperty Bar() As type
Set (value As type)
instructions
End Set
End ComputedProperty
PHP function __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
} }
Perl sub 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 colspan=3 Шаблон:N/a
Ruby def bar
instructions
expression resulting in return value
end
def bar=(value)
instructions
end
def bar
instructions
expression resulting in return value
end
def bar=(value)
instructions
end
Windows PowerShell Add-Member
«-MemberType »ScriptProperty
«-Name »Bar «-Value »{ instructions ... return value }
«-SecondValue »{ instructions }
-InputObject variable
Add-Member
«-MemberType »ScriptProperty
«-Name »Bar «-Value »{ instructions ... return value}
-InputObject variable
Add-Member
«-MemberType »ScriptProperty
«-Name »Bar -SecondValue { instructions }
-InputObject variable
OCaml colspan=3 Шаблон:N/a
F# member this.Bar with get() = expression and set(value) = expression member this.Bar = expression member 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 }
COBOL METHOD-ID. GET PROPERTY bar.
DATA DIVISION.
LINKAGE SECTION.
return-var declaration
PROCEDURE DIVISION RETURNING return-var.
    instructions

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

    instructions

END METHOD.

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

END METHOD.

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

END METHOD.

Cobra pro bar «as type»
Шаблон:Keypress get
Шаблон:KeypressШаблон:Keypress instructions
Шаблон:KeypressШаблон:Keypress return value
Шаблон:Keypress set
Шаблон:KeypressШаблон:Keypress instructions
get bar «as type»
Шаблон:Keypress instructions
Шаблон:Keypress return value
set bar «as type»
Шаблон:Keypress instructions
ISLISP colspan=3 Шаблон:N/a

Automatically implemented

read-write read-only write-only
ABAP Objects colspan=3 Шаблон:N/a
C++ colspan=3 Шаблон:N/a
C# type Bar { get; set; } type Bar { get; private set; } type Bar { private get; set; }
D colspan=3 Шаблон:N/a
Java colspan=3 Шаблон:N/a
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;
Шаблон:N/a
Swift var bar : type let bar : type Шаблон:N/a
Eiffel
Python @property
def bar(self):
Шаблон:Keypressinstructions
@bar.setter
def bar(self, value):
Шаблон:Keypressinstructions
@property
def bar(self):
Шаблон:Keypressinstructions
bar = property()
@bar.setter
def bar(self, value):
Шаблон:Keypressinstructions
Visual Basic .NET Property Bar As type« = initial_value» (VB 10)
PHP
Perl[35] use 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 colspan=3 Шаблон:N/a
Ruby attr_accessor :bar attr_reader :bar attr_writer :bar
Windows PowerShell
OCaml colspan=3 Шаблон:N/a
F# member val Bar = value with get, set
COBOL level-number bar clauses PROPERTY. level-number bar clauses PROPERTY «WITH» NO SET. level-number bar clauses PROPERTY «WITH» NO GET.
Cobra pro bar from var «as type» get bar from var «as type» set bar from var «as type»

Overloaded operators

Standard operators

unary binary function call
ABAP Objects colspan=3 Шаблон:N/a
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 } Шаблон:N/a
D type 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 rowspan=2 colspan=3 Шаблон:N/a
Objective-C
Swift func symbol(operand1 : type) -> returntype { instructions } (outside class) func symbol(operand1 : type1, operand2 : type2) -> returntype { instructions } (outside class)
Eiffel[36] op_name alias "symbol": TYPE
do instructions end
op_name alias "symbol" (operand: TYPE1): TYPE2
do instructions end
Python def __opname__(self):
Шаблон:Keypress
instructions
Шаблон:Keypress return
value
def __opname__(self, operand2):
Шаблон:Keypress
instructions
Шаблон:Keypress return
value
def __call__(self«, parameters»):
Шаблон:Keypress
instructions
Шаблон:Keypress return
value
Visual Basic .NET Shared Operator symbol(operand As type) As type
instructions
End Operator
Shared Operator symbol(operand1 As type, operand2 As type) As type
instructions
End Operator
Шаблон:N/a
Xojo Function Operator_name(operand As type) As type
instructions
End Function
colspan=2 Шаблон:N/a
PHP [37] function __invoke(«parameters») { instructions } (PHP 5.3+)
Perl use 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 }
Ruby def symbol
instructions
expression resulting in return value
end
def symbol(operand2)
instructions
expression resulting in return value
end
Шаблон:N/a
Windows PowerShell rowspan=2 colspan=3 Шаблон:N/a
OCaml
F# static member (symbol) operand = expression static member (symbol) (operand1, operand2) = expression Шаблон:N/a
COBOL colspan=3 Шаблон:N/a
ISLISP colspan=3 Шаблон:N/a

Indexers

read-write read-only write-only
ABAP Objects colspan=3 Шаблон:N/a
APL (Dyalog) :Property Numbered Default name
result ← Get
instructions

∇ Set arguments
instructions

:EndProperty Bar
:Property Numbered Default Bar
result ← Get
instructions

:EndProperty Bar
:Property Numbered Default Bar
∇ Set arguments
instructions

: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 } }
D type opIndex(type index) { instructions }
type opIndexAssign(type value, type index) { instructions }
type opIndex(type index) { instructions } type opIndexAssign(type value, type index) { instructions }
Java colspan=3 Шаблон:N/a
Objective-C (recent Clang compiler) Шаблон:N/a - (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 }
Swift subscript (index : type) -> returntype { get { instructions } set«(newIndex)» { instructions } } subscript (index : type) -> returntype { instructions }
Eiffel[36] bracket_name alias "[]" (index: TYPE): TYPE assign set_item
do instructions end
set_item (value: TYPE; index: TYPE):
do instructions end
bracket_name alias "[]" (index: TYPE): TYPE
do instructions end
Python def __getitem__(self, index):
Шаблон:Keypress instructions
Шаблон:Keypress return value
def __setitem__(self, index, value):
Шаблон:Keypress instructions
def __getitem__(self, index):
Шаблон:Keypress instructions
Шаблон:Keypress return value
def __setitem__(self, index, value):
Шаблон:Keypress instructions
Visual Basic .NET Default Property Item(Index As type) As type
Get
instructions
End Get
Set(ByVal
Value As type)
instructions
End Set
End Property
Default ReadOnly Property Item(Index As type) As type
Get
instructions
End Get
End Property
Default WriteOnly Property Item(Index As type) As type
Set(ByVal
Value As type)
instructions
End Set
End Property
PHP [38]
Perl [39]
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; }
Шаблон:N/a
Ruby def [](index)
instructions
expression resulting in return value
end
def []=(index, value)
instructions
end
def [](index)
instructions
expression resulting in return value
end
def []=(index, value)
instructions
end
Windows PowerShell rowspan=2 colspan=3 Шаблон:N/a
OCaml
F# member thisШаблон:Not a typoItem with get(index) = expression and set index value = expression member thisШаблон:Not a typoItem with get(index) = expression member thisШаблон:Not a typoItem with set index value = expression
COBOL colspan=3 Шаблон:N/a
Cobra pro[index «as type»] as type
Шаблон:Keypress get
Шаблон:KeypressШаблон:Keypress instructions
Шаблон:KeypressШаблон:Keypress return value
Шаблон:Keypress set
Шаблон:KeypressШаблон:Keypress instructions
get[index «as type»] as type
Шаблон:Keypress instructions
Шаблон:Keypress return value
set[index «as type»] as type
Шаблон:Keypress instructions

Type casts

downcast upcast
ABAP Objects colspan=2 Шаблон:N/a
C++ operator returntype() { instructions }
C# static explicit operator returntype(type operand) { instructions } static implicit operator returntype(type operand) { instructions }
D T opCast(T)() if (is(T == type)) { instructions }
eC property T { get { return «conversion code»; } }
Java rowspan=4 colspan=2 Шаблон:N/a
Objective-C
Eiffel[36]
Python
Visual Basic .NET Shared Narrowing Operator CType(operand As type) As returntype
instructions
End Operator
Shared Widening Operator CType(operand As type) As returntype
instructions
End Operator
PHP rowspan=2 colspan=2 Шаблон:N/a
Perl
Raku multi method type«($self:)» is export { instructions }
Ruby rowspan=3 colspan=2 Шаблон:N/a
Windows PowerShell
OCaml
F#
COBOL colspan=2 Шаблон:N/a

Member access

How to access members of an object x

object member class member namespace member
method field property
ABAP Objects x->methodparameters»).[40] x->field Шаблон:N/a x=>field or x=>methodparameters[40]»). Шаблон:N/a
C++ x.method(parameters) or
ptr->method(parameters)
x.field or
ptr->field
cls::member ns::member
Objective-C [x method«:parameter «bar:parameter ...»»] x->field x.property (2.0 only) or
[x property]
[cls method«:parameter «bar:parameter ...»»]
Smalltalk x method«:parameter «bar:parameter ...»» Шаблон:N/a cls method«:parameter «bar:parameter ...»»
Swift x.method(parameters) x.property cls.member
APL (Dyalog) left argument» x.method «right argument(s)» x.field x.property cls.member ns.member
C# x.method(parameters)
Java Шаблон:N/a
D x.property
Python
Visual Basic .NET
Xojo
Windows PowerShell [cls]::member
F# Шаблон:N/a cls.member
eC x.method«(parameters)» x.field x.property cls::member ns::member
Eiffel x.method«(parameters)» x.field {cls}.member rowspan=2 Шаблон:N/a
Ruby Шаблон:N/a x.property cls.member
PHP x->method(parameters) x->field x->property cls::member ns\member
Perl x->method«(parameters)» x->{field} cls->method«(parameters)» ns::member
Raku x.method«(parameters)» or
x!method«(parameters)»
x.field or
x!field
cls.method«(parameters)» or
cls!method«(parameters)»
ns::member
OCaml x#method «parameters» colspan=2 Шаблон:N/a
JavaScript x.method(parameters)
x["method"](parameters)
x.field
x["field"]
x.property
x["property"]
cls.member
cls["member"]
Шаблон:N/a
COBOL INVOKE x "method" «USING parameters» «RETURNING result» or
x::"method"«(«parameters»)»
Шаблон:N/a property OF x INVOKE cls "method" «USING parameters» «RETURNING result» or
cls::"method"«(«parameters»)» or
property OF cls
Шаблон:N/a
Cobra x.method«(parameters)» x.field x.property cls.member ns.member

Member availability

Has member? Handler for missing member
Method Field Method Field
APL (Dyalog) 3=x.⎕NC'method' 2=x.⎕NC'method' colspan=2 Шаблон:N/a
ABAP Objects rowspan=2 colspan=4 Шаблон:N/a
C++
Objective-C (Cocoa) [x respondsToSelector:@selector(method)] Шаблон:N/a forwardInvocation: Шаблон:N/a
Smalltalk x respondsTo: selector Шаблон:N/a doesNotUnderstand: Шаблон:N/a
C# (using reflection)
eC
Java
D opDispatch()
Eiffel colspan=4 Шаблон:N/a
Python hasattr(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)
Ruby x.respond_to?(:method) Шаблон:N/a method_missing() Шаблон:N/a
PHP method_exists(x, "method") property_exists(x, "field") __call() __get() / __set()
Perl x->can("method") exists x->{field} AUTOLOAD
Raku x.can("method") x.field.defined AUTOLOAD
OCaml colspan=4 Шаблон:N/a
JavaScript typeof x.method === "function" field in x
COBOL colspan=4 Шаблон:N/a

Special variables

current object current object's parent object null reference Current Context of Execution
Smalltalk self super nil thisContext
ABAP Objects me super initial
APL (Dyalog) ⎕THIS ⎕BASE ⎕NULL
C++ *this [41] NULL, nullptr
C# this base[42] null
Java super[42]
D
JavaScript super[42] (ECMAScript 6) null, undefined[43]
eC this null
Objective-C self super[42] nil
Swift self super[42] nil[44]
Python self[45] super(current_class_name, self)[7]
super() (3.x only)
None
Visual Basic .NET Me MyBase Nothing
Xojo Me / Self Parent Nil
Eiffel Current Precursor «{superclass}» «(args)»[42][46] Void
PHP $this parent[42] null
Perl $self[45] $self->SUPER[42] undef
Raku self SUPER Nil
Ruby self super«(args)»[47] nil binding
Windows PowerShell $this $NULL
OCaml self[48] super[49] Шаблон:N/a[50]
F# this base[42] null
COBOL SELF SUPER NULL
Cobra this base nil

Special methods

String representation Object copy Value equality Object comparison Hash code Object ID
Human-readable Source-compatible
ABAP Objects colspan=7 Шаблон:N/a
APL (Dyalog) x ⎕SRC x ⎕NS x x = y colspan=2 Шаблон:N/a
C++ x == y[51] pointer 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)
Java x.toString() x.clone()[52] x.equals(y) x.compareTo(y)[53] x.hashCode() System.identityHashCode(x)
JavaScript x.toString()
D x.toString() or
std.conv.to!string(x)
x.stringof x == y or
x.opEquals(y)
x.opCmp(y) x.toHash()
eC x.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.description x.debugDescription [x copy][54] [x isEqual:y] [x compare:y][55] x.hash pointer to object can be converted into an integer ID
Swift x.description[56] x.debugDescription[57] x == y[58] x < y[59] x.hashValue[60] reflect(x).objectIdentifier!.uintValue()
Smalltalk x displayString x printString x copy x = y x hash x identityHash
Python str(x)[61] repr(x)[62] copy.copy(x)[63] x == y[64] cmp(x, y)[65] hash(x)[66] id(x)
Visual Basic .NET x.ToString() x.Clone() x.Equals(y) x.CompareTo(y) x.GetHashCode()
Eiffel x.out x.twin x.is_equal(y) When x is COMPARABLE, one can simply do x < y When x is HASHABLE, one can use x.hash_code When x is IDENTIFIED, one can use x.object_id
PHP $x->__toString() clone x[67] x == y spl_object_hash(x)
Perl "$x"[68] Data::Dumper->Dump([$x],[Шаблон:'xШаблон:'])[69] Storable::dclone($x)[70] Scalar::Util::refaddr( $x )[71]
Raku ~x[68] x.perl x.clone x eqv y x cmp y x.WHICH
Ruby x.to_s x.inspect x.dup or
x.clone
x == y or
x.eql?(y)
x <=> y x.hash x.object_id
Windows PowerShell x.ToString() x.Clone() x.Equals(y) x.CompareTo(y) x.GetHashCode()
OCaml Oo.copy x x = y Hashtbl.hash x Oo.id x
F# string x or x.ToString() or sprintf "%O" x sprintf "%A" x x.Clone() x = y or x.Equals(y) compare x y or x.CompareTo(y) hash x or x.GetHashCode()
COBOL colspan=7 Шаблон:N/a

Type manipulation

Get object type Is instance of (includes subtypes) Upcasting Downcasting
Runtime check No check
ABAP Objects colspan=2 Шаблон:N/a[72] = ?=
C++ typeid(x) dynamic_cast<type *>(&x) != nullptr rowspan=8 Шаблон:N/a[73] dynamic_cast<type*>(ptr) (type*) ptr or
static_cast<type*>(ptr)
C# x.GetType() x is type (type) x or x as type
D typeid(x) cast(type) x
Delphi x is type x as type
eC x._class eClass_IsDerived(x._class, type) (type) x
Java x.getClass() x instanceof class (type) x
Objective-C (Cocoa) [x class][74] [x isKindOfClass:[class class]] (type*) x
Swift x.dynamicType x is type x as! type
x as? type
JavaScript x.constructor (If not rewritten.) x instanceof class colspan=3 Шаблон:N/a[75]
Visual Basic .NET x.GetType() TypeOf x Is type Шаблон:N/a[73] CType(x, type) or TryCast(x, type)
Xojo Introspection.GetType(x) x IsA type Шаблон:N/a CType(x, type) Шаблон:N/a
Eiffel x.generating_type attached {TYPE} x attached {TYPE} x as down_x
Python type(x) isinstance(x, type) colspan=3 rowspan=3 Шаблон:N/a[75]
PHP get_class(x) x instanceof class
Perl ref(x) x->isa("class")
Raku x.WHAT x.isa(class) Шаблон:N/a[73] type(x) or
x.type
Ruby x.class x.instance_of?(type) or
x.kind_of?(type)
colspan=3 rowspan=2 Шаблон:N/a[75]
Smalltalk x class x isKindOf: class
Windows PowerShell x.GetType() x -is [type] Шаблон:N/a[73] [type]x or x -as [type]
OCaml colspan=2 Шаблон:N/a[76] (x :> type) colspan=2 Шаблон:N/a
F# x.GetType() x :? type (x :?> type)
COBOL colspan=2 Шаблон:N/a x AS type[73] colspan=2 Шаблон:N/a

Namespace management

Import namespace Import item
qualified unqualified
ABAP Objects
C++ using namespace ns; using ns::item ;
C# using ns; using item = ns.item;
D import ns; import ns : item;
Java import ns.*; import ns.item;
Objective-C
Visual Basic .NET Imports ns
Eiffel
Python import ns from ns import * from ns import item
PHP use ns; use ns\item;
Perl use ns; use ns qw(item);
Raku
Ruby
Windows PowerShell
OCaml open ns
F#
COBOL colspan=3 Шаблон:N/a

Contracts

Precondition Postcondition Check Invariant Loop
ABAP Objects colspan=5 rowspan=2 Шаблон:N/a
C++
C# Spec#:
type foo( «parameters» )
    requires expression
{
    body
}
Spec#:
type foo( «parameters» )
    ensures expression
{
    body
}
Java colspan=5 rowspan=3 Шаблон:N/a
Objective-C
Visual Basic .NET
D f
in { asserts }
body{
instructions }
f
out (result) { asserts }
body{
instructions }
assert(expression) invariant() { expression }
Eiffel f
require tag: expression
do end
f
do
ensure
tag: expression
end
f
do
check tag: expression end
end
class X
invariant tag: expression
end
from instructions
invariant
tag: expression
until
expr
loop
instructions
variant
tag: expression
end
Python colspan=5 rowspan=3 Шаблон:N/a
PHP
Perl
Raku PRE { condition } POST { condition }
Ruby colspan=5 rowspan=5 Шаблон:N/a
Windows PowerShell
OCaml
F#
COBOL

See also

References and notes

Шаблон:Reflist

  1. parameter = argument may be repeated if the constructor has several parameters
  2. SAP reserved to himself the use of destruction
  3. 3,00 3,01 3,02 3,03 3,04 3,05 3,06 3,07 3,08 3,09 3,10 3,11 This language uses garbage collection to release unused memory.
  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. OCaml objects can be created directly without going through a class.
  7. 7,0 7,1 7,2 7,3 7,4 7,5 7,6 This language supports multiple inheritance. A class can have more than one parent class
  8. 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.
  9. Usually the @interface portion is placed into a header file, and the @interface portion is placed into a separate source code file.
  10. In Python interfaces are classes which methods have pass as their bodies
  11. The class is an Object.
    Just send a message to the superclass (st-80) or the destination namespace (Visualworks).
  12. The namespace is an Object.
    Just send a message to the parent namespace.
  13. 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.
  14. 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
  15. 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.
  16. Any Eiffel procedure can be used as a creation procedure, aka constructors. See Eiffel paragraph at Constructor (computer science).
  17. Implementing {DISPOSABLE}.dispose ensures that dispose will be called when object is garbage collected.
  18. 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.
  19. This syntax is usually used to overload constructors
  20. In JavaScript, constructor is an object.
  21. Constructors can be emulated with a factory method returning a class instance.
  22. 22,0 22,1 22,2 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
  23. 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.
  24. 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.
  25. Just send a message to the class
    class addInstVarName: field.
    class removeInstVarName: field.
    
  26. 26,0 26,1 26,2 26,3 Just assign a value to it in a method
  27. 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.
  28. All class data is 'private' because the COBOL standard does not specify any way to access it.
  29. 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.
  30. In ABAP, the return parameter name is explicitly defined in the method signature within the class definition
  31. 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
  32. 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.
  33. 33,0 33,1 Just assign a function to it in a method
  34. 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())
    
  35. these examples need the Class::Accessor module installed
  36. 36,0 36,1 36,2 Although Eiffel does not support overloading of operators, it can define operators
  37. PHP does not support operator overloading natively, but support can be added using the "operator" PECL package.
  38. The class must implement the ArrayAccess interface.
  39. The class must overload '@{}' (array dereference) or subclass one of Tie::Array or Tie::StdArray to hook array operations
  40. 40,0 40,1 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
  41. 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]
  42. 42,0 42,1 42,2 42,3 42,4 42,5 42,6 42,7 42,8 The keyword here is not a value, and it can only be used to access a method of the superclass.
  43. But be afraid, they have not the same value.
  44. only for Optional types
  45. 45,0 45,1 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.
  46. "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.
  47. "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.
  48. 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.
  49. 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.
  50. 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.
  51. assuming that "x" and "y" are the objects (and not pointers). Can be customized by overloading the object's == operator
  52. 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.
  53. The class should implement the interface Comparable for this method to be standardized.
  54. Implemented by the object's copyWithZone: method
  55. compare: is the conventional name for the comparison method in Foundation classes. However, no formal protocol exists
  56. Only if object conforms to the Printable protocol
  57. Only if object conforms to the DebugPrintable protocol
  58. Only if object conforms to the Equatable protocol
  59. Only if object conforms to the Comparable protocol
  60. Only if object conforms to the hashValue protocol
  61. Can be customized by the object's __str__() method
  62. Can be customized by the object's __repr__() method
  63. Can be customized by the object's __copy__() method
  64. Can be customized by the object's __eq__() method
  65. Only in Python 2.x and before (removed in Python 3.0). Can be customized by the object's __cmp__() method
  66. Can be customized by the object's __hash__() method. Not all types are hashable (mutable types are usually not hashable)
  67. Can be customized by the object's __clone() method
  68. 68,0 68,1 Can be customized by overloading the object's string conversion operator
  69. This example requires useing Data::Dumper
  70. This example requires useing Storable
  71. This example requires useing Scalar::Util
  72. Run-time type information in ABAP can be gathered by using different description Classes like CL_ABAP_CLASSDESCR.
  73. 73,0 73,1 73,2 73,3 73,4 Upcasting is implicit in this language. A subtype instance can be used where a supertype is needed.
  74. 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.
  75. 75,0 75,1 75,2 This language is dynamically typed. Casting between types is unneeded.
  76. This language doesn't give run-time type information. It is unneeded because it is statically typed and downcasting is impossible.