Movatterモバイル変換


[0]ホーム

URL:


Jump to content
WikipediaThe Free Encyclopedia
Search

Comparison of programming languages (object-oriented programming)

From Wikipedia, the free encyclopedia
This article has multiple issues. Please helpimprove it or discuss these issues on thetalk page.(Learn how and when to remove these messages)
This article mayrequirecleanup to meet Wikipedia'squality standards. The specific problem is:This article'sreference section contains many footnotes, but lists no external references or sources. Please helpimprove this article if you can.(June 2013) (Learn how and when to remove this message)
This articleneeds additional citations forverification. Please helpimprove this article byadding citations to reliable sources. Unsourced material may be challenged and removed.
Find sources: "Comparison of programming languages" object-oriented programming – news ·newspapers ·books ·scholar ·JSTOR
(January 2025) (Learn how and when to remove this message)
(Learn how and when to remove this message)
Comparison of
programming languages

Thiscomparison of programming languages compares howobject-oriented programming languages such asC++,Java,Smalltalk,Object Pascal,Perl,Python, and others manipulatedata structures.

Object construction and destruction

[edit]
constructiondestruction
ABAP Objectsdata variabletype 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=newclass«(parameters)»;[5]
delete pointer;
C#class variable= new class(parameters);variable.Dispose();[3]
Java[3]
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 ...»];
[variablerelease];
Swiftlet variable= class(parameters)
Pythonvariable= class(parameters)del variable[3] (Normally not needed)
Visual Basic .NETDim variableAs New class(parameters)variable.Dispose()[3]
XojoDim variableAs New class(parameters)variable =Nil
Eiffelcreate 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;
Rubyvariable= class.new«(parameters)»[3]
Windows PowerShell$variable= New-Object«-TypeName» class ««-ArgumentList» parameters»Remove-Variable «-Name» variable
OCamllet variable= new class «parameters» or
let variable= object membersend[6]
[3]
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:
Pointx:10y:20.Arraywith:-1with:3with:2.
JavaScriptvar variable= new class«(parameters)» or
var variable= { «key1: value1«, key2: value2 ...»»}
[3]
Object Pascal (Delphi)ClassVar:= ClassType.ConstructorName(parameters);ClassVar.Free;
Scala
valobj=newObject// no parametersvalobj=newObject(arg0,arg1,arg2...)valobj=Object(arg0,arg1,arg2...)// case classvalobj=newObject(arg0,arg1,param1=value1,...)// named parameters
[3]
COBOLINVOKE class"NEW"RETURNING variable or
MOVE 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] ..])))[3]

Class declaration

[edit]
classprotocolnamespace
ABAP Objectsclass namedefinition «inheriting from parentclass». «interfaces: interfaces.» method_and_field_declarationsendclass.
class nameimplementation. method_implementationsendclass.
interface name. membersendinterface.
APL (Dyalog):Class name «:parentclass» «,interfaces»
members
:EndClass
:Interface name
members
:EndInterface
:Namespace name
members
:EndNamespace
C++classname« : publicparentclasses[7]» {members };namespacename {members }
C#classname« :«parentclass»«, interfaces»» {members }interface name« : parentinterfaces»{ members}
Dmodulename;
members
eCclass name« : base class»{ «default member values assignments» «members»}namespace name;
Javaclassname« extendsparentclass»« implementsinterfaces» {members }interface name« extends parentinterfaces»{ members}packagename; members
PHPnamespacename;members
Objective-C@interfacename« :parentclass»[8]«< protocols>» {instance_fields }method_and_property_declarations @end
@implementation
name method_implementations @end
[9]
@protocolname«< parentprotocols>» members @end[10]
Swiftclassname« :«parentclass»«, protocols»» {members }protocolname« :parentprotocols» {members }
Pythonclassname«(parentclasses[7])»:
Tab ↹
members
[11]__all__ = [member1,member2,... ]
Visual Basic .NETClassname« Inheritsparentclass»« Implementsinterfaces»
members
End Class
Interfacename« Inheritsparentinterfaces»
members
End Interface
Namespacename
members
End Namespace
XojoClassname« Inheritsparentclass»« Implementsinterfaces»
members
End Class
Interfacename« Inheritsparentinterfaces»
members
End Interface
Modulename
members
End Module
Eiffelclassname« inheritparentclasses[7]»
members
end
Perlpackagename;«@ISA = qw(parentclasses[7]);» members1;packagename; members
Rakuclassname «is parentclass «is parentclass ...[7]»» «does role «does role ...»»{ members}rolename «does role «does role ...»»{ members}module name{ members}
Rubyclassname« < parentclass»
members
end
modulename
members
end
Windows PowerShell
OCamlclassname «parameters» = object«(self)» «inheritparentclass «parameters» «inheritparentclass «parameters» ...[7]»» membersendmodule name
members
F#typename«(parameters)»«as this»= class «inheritparentclass«(parameters)» «as base»» members «interface interfacewith implementation «interface interfacewith implementation ...»»endtypename= interface membersendnamespace name
members
Smalltalk[12][13]
JavaScript (ES6)class name «extends parentclass»{ members}
Object Pascal (Delphi)

ClassName = Class «(ClassParent, Interfaces)»
private
// Private members(include Methods and Fields)
public
// Public members
protected
// Protected members
published
// Published members
end;

packagename; members
Scala
classConcreteClass(constructorparams)extendsParentClasswithTrait1withTrait2withTrait2{// members}
traitTraitNameextendsOtherTrait1withOtherTrait2withOtherTrait3{// members}
packagename
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 ↹ members
interface name «inherits parentinterfaces»
Tab ↹ members
namespace name
Tab ↹ members
ISLISP(defclass name (base-class) ((x:initform 0:accessor get-x:initarg x)) (:abstractp nil))

Class members

[edit]

Constructors and destructors

[edit]
constructordestructorfinalizer[14]
ABAP Objectsmethods constructor «importing parameter = argument»
method constructor. instructionsendmethod.
[15]
APL (Dyalog) name
:Implements Constructor «:Base «expr»»
instructions
name
:Implements Destructor
instructions
C++class(«parameters»)«:initializers[16]» {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 }
Eiffel[17][18]
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 ↹ instructions
def __del__(self):
Tab ↹ instructions
Visual Basic .NETSub New(«parameters»)
instructions
End Sub
Sub Dispose()
instructions
End Sub
Overrides Sub Finalize()
instructions
End Sub
XojoSub Constructor(«parameters»)
instructions
End Sub
Sub 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 instructions[19]
F#do instructions or
new(parameters) = expression
[20]
member this.Dispose() = instructionsoverride this.Finalize() = instructions
JavaScriptfunction name(«parameters»){ instructions}[21]
JavaScript (ES6)constructor(«parameters») { instructions}
COBOL[22]
Cobracue init(parameters)
Tab ↹base.init
Tab ↹ instructions
def dispose
Tab ↹ instructions
ISLISP(defmethod initialize-object ((instance <class-name>) initvalues)

Fields

[edit]
publicprivateprotectedfriend
ABAP Objectspublic section.[23] data fieldtype type.private section.[23] data fieldtype type.protected section.[23] data fieldtype type.[24]
APL (Dyalog):Field Public field « value»:Field «Private» field « value»
C++public:type field;private:type field;protected:type field;[25]
C#publictype field «= value»;privatetype field «= value»;protectedtype field «= value»;internal type field «= value»;
Dpackage type field «= value»;
Javaprotectedtype field «= value»;type field «= value»;
eCpublic type field;private type field;
Eiffelfeature
field: TYPE
feature {NONE}
field: TYPE
feature {current_class}
field: TYPE
feature {FRIEND}
field: TYPE
Objective-C@publictype field;@privatetype field;@protectedtype field;@packagetype field;
Swift
Smalltalk[26]
Pythonself.field =value[27][28]
Visual Basic .NETPublicfield Astype «= value»Privatefield Astype «= value»Protectedfield Astype «= value»Friendfield Astype «= value»
XojoPublicfield Astype «= value»Privatefield Astype «= value»Protectedfield Astype «= value»
PHPpublic $field «= value»;private $field «= value»;protected $field «= value»;
Perl$self->{field} =value;[27]
Rakuhas« type »$.field« is rw»has« type »$!field
Ruby@field= value[27]
Windows PowerShellAdd-Member
«-MemberType»NoteProperty
«-Name»Bar «-Value»value
-InputObjectvariable
OCamlval «mutable» field= value
F#let «mutable» field= value
JavaScriptthis.field =value
this["field"] = value
[27]
COBOLlevel-number field clauses.[29]
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

[edit]
basic/void methodvalue-returning method
ABAP Objectsmethods name «importing parameter = argument» «exporting parameter = argument» «changing parameter = argument» «returning value(parameter)»
method name. instructionsendmethod.
[30]
[31]
APL (Dyalog) «left argument» name «right arguments»
instructions
result «left argument» name «right arguments»
instructions
C++[32]
type foo(«parameters»);

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

type class::foo(«parameters») {instructions }[33]
voidfoo(«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
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; }
Swiftfuncfoo(«parameters») {instructions }funcfoo(«parameters») ->type {instructions...return value }
Pythondeffoo(self«, parameters»):
Tab ↹
instructions
deffoo(self«, parameters»):
Tab ↹
instructions
Tab ↹ return
value
Visual Basic .NETSubFoo(«parameters»)
instructions
End Sub
FunctionFoo(«parameters») Astype
instructions
...
Return value
End Function
XojoSubFoo(«parameters»)
instructions
End Sub
FunctionFoo(«parameters») Astype
instructions
...
Return value
End Function
PHPfunctionfoo(«parameters»)«: void» {instructions }functionfoo(«parameters»)«:type» {instructions ...return value; }
Perlsubfoo { my ($self«,parameters») = @_;instructions }subfoo { my ($self«,parameters») = @_;instructions ...return value; }
Raku«has »«multi »methodfoo(««$self: »parameters») {instructions }«has «type »»«multi »methodfoo(««$self: »parameters») {instructions ...return value; }
Rubydeffoo«(parameters)»
instructions
end
deffoo«(parameters)»
instructions
expression resulting in return value
end
or
deffoo«(parameters
instructions
return value
end
Windows PowerShellAdd-Member«-MemberType» ScriptMethod«-Name» foo «-Value» {«param(parameters)»instructions } -InputObjectvariableAdd-Member«-MemberType» ScriptMethod«-Name» foo «-Value» {«param(parameters)»instructions ...return value} -InputObjectvariable
OCamlmethod foo «parameters»= expression
F#member this.foo(«parameters») = expression
JavaScriptthis.method = function(«parameters») {instructions}
name«.prototype.method = function(«parameters») {instructions}
[34]
this.method = function(«parameters») {instructions...return value;}
name«.prototype.method = function(«parameters») {instructions...return value;}
[34]
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 declaration
PROCEDURE DIVISION« USING parameters»RETURNING result-var.
    instructions

END METHOD foo.

Cobradef foo(parameters)
Tab ↹ instructions
def foo(parameters) as type
Tab ↹ instructions
Tab ↹return value
ISLISP(defgeneric method (arg1 arg2))
(defmethod method ((arg1 <class1> arg2 <class2>) ...)

Properties

[edit]

How to declare a property named "Bar"

Manually implemented

[edit]
read-writeread-onlywrite-only
ABAP Objects
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++
C#type Bar{
get {
instructions ...returnvalue;}
set {
instructions } }
type Bar{ get {instructions ...returnvalue;} }type Bar{ set {instructions } }
D@property type bar() {instructions ...returnvalue;}
@property
type bar(type value) {instructions ...returnvalue;}
@property type bar() {instructions ...returnvalue;}@property type bar(type value) {instructions ...returnvalue;}
eCproperty type Bar{
get {
instructions ...returnvalue;}
set {
instructions } }
property type Bar{ get {instructions ...returnvalue;} }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: TYPEassign set_x
feature -- Settings
set_x (a_x:like x)do instructionsensure x_set: verificationend
Pythondef setBar(self,value):
Tab ↹ instructions
def
getBar(self):
Tab ↹
instructions
Tab ↹return value
bar = property(getBar, setBar)
[35]
def getBar(self):
Tab ↹ instructions
Tab ↹return value
bar = property(getBar)
def setBar(self,value):
Tab ↹ instructions
bar = property(fset =setBar)
Visual Basic .NETPropertyBar() Astype
Get
instructions
Return value
End Get
Set (ByVal
Value Astype)
instructions
End Set
End Property
ReadOnly PropertyBar() Astype
Get
instructions
Return value
End Get
End Property
WriteOnly PropertyBar() Astype
Set (ByValValue Astype)
instructions
End Set
End Property
XojoComputedPropertyBar() Astype
Get
instructions
Return value
End Get
Set (ByVal
Value Astype)
instructions
End Set
End ComputedProperty
ComputedPropertyBar() Astype
Get
instructions
Return value
End Get
End ComputedProperty
ComputedPropertyBar() Astype
Set (value Astype)
instructions
End Set
End 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
Rubydefbar
instructions
expression resulting in return value
end
defbar=(value)
instructions
end
defbar
instructions
expression resulting in return value
end
defbar=(value)
instructions
end
Windows PowerShellAdd-Member
«-MemberType»ScriptProperty
«-Name»Bar «-Value»{ instructions ...return value }
«-SecondValue»{ instructions}
-InputObjectvariable
Add-Member
«-MemberType»ScriptProperty
«-Name»Bar «-Value»{ instructions ...return value}
-InputObjectvariable
Add-Member
«-MemberType»ScriptProperty
«-Name»Bar-SecondValue { instructions}
-InputObjectvariable
OCaml
F#member this.Barwith get() = expressionand set(value) = expressionmember this.Bar= expressionmember this.Barwith set(value) = expression
JavaScript (ES6)get bar(«parameters»){ instructions ...returnvalue}setbar(«parameters») {instructions}get bar(«parameters»){ instructions ...returnvalue}setbar(«parameters») {instructions}
COBOLMETHOD-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.

Cobrapro bar «as type»
Tab ↹get
Tab ↹Tab ↹ instructions
Tab ↹Tab ↹return value
Tab ↹set
Tab ↹Tab ↹ instructions
get bar «as type»
Tab ↹ instructions
Tab ↹return value
set bar «as type»
Tab ↹ instructions
ISLISP

Automatically implemented

[edit]
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@property
def bar(self):
Tab ↹instructions
@bar.setter
def bar(self, value):
Tab ↹instructions
@property
def bar(self):
Tab ↹instructions
bar= property()
@bar.setter
def bar(self, value):
Tab ↹instructions
Visual Basic .NETProperty BarAs type« = initial_value» (VB 10)
PHP
Perl[36]usebaseqw(Class::Accessor);
__PACKAGE__->mk_accessors('Bar');
usebaseqw(Class::Accessor);
__PACKAGE__->mk_ro_accessors('Bar');
usebaseqw(Class::Accessor);
__PACKAGE__->mk_wo_accessors('Bar');
Raku
Rubyattr_accessor :barattr_reader :barattr_writer :bar
Windows PowerShell
OCaml
F#member val Bar= valuewith get, set
COBOLlevel-number bar clausesPROPERTY.level-number bar clausesPROPERTY «WITH» NO SET.level-number bar clausesPROPERTY «WITH» NO GET.
Cobrapro barfrom var «as type»get barfrom var «as type»set barfrom var «as type»

Overloaded operators

[edit]

Standard operators

[edit]
unarybinaryfunction call
ABAP Objects
C++typeoperator symbol() {instructions }typeoperator symbol(type operand2) {instructions }typeoperator () («parameters») {instructions }
C#statictype operatorsymbol(type operand) {instructions }statictype operatorsymbol(type operand1,type operand2) {instructions }
DtypeopUnary(string s)() if (s == "symbol") {instructions }typeopBinary(string s)(type operand2) if (s == "symbol") {instructions }
typeopBinaryRight(string s)(type operand1) if (s == "symbol") switch (s) {instructions }
typeopCall(«parameters») {instructions }
Java
Objective-C
Swiftfunc symbol(operand1: type) ->returntype {instructions } (outside class)func symbol(operand1: type1,operand2: type2) ->returntype {instructions } (outside class)
Eiffel[37]op_namealias "symbol": TYPE
do instructionsend
op_namealias "symbol" (operand: TYPE1): TYPE2
do instructionsend
Pythondef __opname__(self):
Tab ↹
instructions
Tab ↹ return
value
def __opname__(self,operand2):
Tab ↹
instructions
Tab ↹ return
value
def __call__(self«,parameters»):
Tab ↹
instructions
Tab ↹ return
value
Visual Basic .NETShared Operatorsymbol(operand Astype) Astype
instructions
End Operator
Shared Operatorsymbol(operand1 Astype,operand2 Astype) Astype
instructions
End Operator
XojoFunction Operator_name(operand Astype) Astype
instructions
End Function
PHP[38]function __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 ...returnvalue;} or
«our «type »»«multi »method postfix:<symbol> («$operand: ») { instructions ...returnvalue;} or
«our «type »»«multi »method circumfix:<symbol1 symbol2> («$operand: ») { instructions ...returnvalue;}
«our «type »»«multi »method infix:<symbol> («$operand1: » type operand2) { instructions ...returnvalue;}«our «type »»«multi »method postcircumfix:<( )> («$self: » «parameters») { instructions}
Rubydefsymbol
instructions
expression resulting in return value
end
defsymbol(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

[edit]
read-writeread-onlywrite-only
ABAP Objects
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 }typeoperator[](type index) {instructions }
C#typethis[type index] {
get{
instructions }
set{
instructions } }
typethis[type index] { get{instructions } }typethis[type index] { set{instructions } }
DtypeopIndex(type index) {instructions }
typeopIndexAssign(type value,type index) {instructions }
typeopIndex(type index) {instructions }typeopIndexAssign(type value,type index) {instructions }
Java
Objective-C (recent Clang compiler)- (id)objectAtIndexedSubscript:(NSUInteger)index {instructions returnvalue; } or
- (id)objectForKeyedSubscript:(id)index {instructions returnvalue; }
- (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 }
Eiffel[37]bracket_namealias "[]" (index: TYPE): TYPEassign set_item
do instructionsend
set_item(value: TYPE; index: TYPE):
do instructionsend
bracket_namealias "[]" (index: TYPE): TYPE
do instructionsend
Pythondef __getitem__(self,index):
Tab ↹ instructions
Tab ↹return value
def __setitem__(self,index,value):
Tab ↹ instructions
def __getitem__(self,index):
Tab ↹ instructions
Tab ↹return value
def __setitem__(self,index,value):
Tab ↹ instructions
Visual Basic .NETDefault Property Item(Index Astype) Astype
Get
instructions
End Get
Set(ByVal
Value Astype)
instructions
End Set
End Property
Default ReadOnly Property Item(Index Astype) Astype
Get
instructions
End Get
End Property
Default WriteOnly Property Item(Index Astype) Astype
Set(ByVal
Value Astype)
instructions
End Set
End Property
PHP[39]
Perl[40]
Raku«our «type »»«multi »method postcircumfix:<[ ]> is rw («$self: » type $index) { instructions ...returnvalue;} or
«our «type »»«multi »method postcircumfix:<{ }> is rw («$self: » type $key) { instructions ...returnvalue;}
«our «type »»«multi »method postcircumfix:<[ ]>(«$self: » type $index) { instructions ...returnvalue;} or
«our «type »»«multi »method postcircumfix:<{ }> («$self: » type $key) { instructions ...returnvalue;}
Rubydef [](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
OCaml
F#member this.Item with get(index) = expressionand setindex value= expressionmember this.Item with get(index) = expressionmember this.Item with setindex value= expression
COBOL
Cobrapro[index «as type»] as type
Tab ↹get
Tab ↹Tab ↹ instructions
Tab ↹Tab ↹return value
Tab ↹set
Tab ↹Tab ↹ instructions
get[index «as type»] as type
Tab ↹ instructions
Tab ↹return value
set[index «as type»] as type
Tab ↹ instructions

Type casts

[edit]
downcastupcast
ABAP Objects
C++operatorreturntype() {instructions }
C#static explicit operatorreturntype(type operand) {instructions }static implicit operatorreturntype(type operand) {instructions }
DTopCast(T)() if (is(T ==type)) {instructions }
eCproperty T{ get { return «conversion code»; } }
Java
Objective-C
Eiffel[37]
Python
Visual Basic .NETShared Narrowing Operator CType(operand Astype) Asreturntype
instructions
End Operator
Shared Widening Operator CType(operand Astype) Asreturntype
instructions
End Operator
PHP
Perl
Rakumulti methodtype«($self:)»is export { instructions}
Ruby
Windows PowerShell
OCaml
F#
COBOL

Member access

[edit]

How to access members of an object x

object memberclass membernamespace member
methodfieldproperty
ABAP Objectsx->methodparameters»).[41]x->fieldx=>field orx=>methodparameters[41]»).
C++x.method(parameters) or
ptr->method(parameters)
x.field or
ptr->field
cls::memberns::member
Objective-C[xmethod«:parameter «bar:parameter ...»»]x->fieldx.property (2.0 only) or
[xproperty]
[cls method«:parameter «bar:parameter ...»»]
Smalltalkxmethod«: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!field
cls.method«(parameters)» or
cls!method«(parameters)»
ns::member
OCamlx#method «parameters»
JavaScriptx.method(parameters)
x["method"](parameters)
x.field
x["field"]
x.property
x["property"]
cls.member
cls["member"]
COBOLINVOKE x"method" «USING parameters» «RETURNING result» or
x::"method"«(«parameters»)»
propertyOF xINVOKE cls"method" «USING parameters» «RETURNING result» or
cls::"method"«(«parameters»)» or
propertyOF cls
Cobrax.method«(parameters)»x.fieldx.propertycls.memberns.member

Member availability

[edit]
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:
SmalltalkxrespondsTo: 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")existsx->{field}AUTOLOAD
Rakux.can("method")x.field.definedAUTOLOAD
OCaml
JavaScripttypeofx.method === "function"fieldin x
COBOL

Special variables

[edit]
current objectcurrent object'sparent objectnull referenceCurrent Context of Execution
SmalltalkselfsupernilthisContext
ABAP Objectsmesuperinitial
APL (Dyalog)⎕THIS⎕BASE⎕NULL
C++*this[42]NULL,nullptr
C#thisbase[43]null
Javasuper[43]
D
JavaScriptsuper[43] (ECMAScript 6)null,undefined[44]
eCthisnull
Objective-Cselfsuper[43]nil
Swiftselfsuper[43]nil[45]
Pythonself[46]super(current_class_name, self)[7]
super() (3.x only)
None
Visual Basic .NETMeMyBaseNothing
XojoMe / SelfParentNil
EiffelCurrentPrecursor «{superclass}» «(args)»[43][47]Void
PHP$thisparent[43]null
Perl$self[46]$self->SUPER[43]undef
RakuselfSUPERNil
Rubyselfsuper«(args)»[48]nilbinding
Windows PowerShell$this$NULL
OCamlself[49]super[50][51]
F#thisbase[43]null
COBOLSELFSUPERNULL
Cobrathisbasenil

Special methods

[edit]
String representationObject copyValue equalityObject comparisonHash codeObject ID
Human-readableSource-compatible
ABAP Objects
APL (Dyalog)x⎕SRC x⎕NS xx= y
C++x== y[52]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)
Javax.toString()x.clone()[53]x.equals(y)x.compareTo(y)[54]x.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][55][x isEqual:y][x compare:y][56]x.hashpointer to object can be converted into an integer ID
Swiftx.description[57]x.debugDescription[58]x== y[59]x< y[60]x.hashValue[61]reflect(x).objectIdentifier!.uintValue()
SmalltalkxdisplayStringxprintStringxcopyx= yxhashxidentityHash
Pythonstr(x)[62]repr(x)[63]copy.copy(x)[64]x== y[65]cmp(x,y)[66]hash(x)[67]id(x)
Visual Basic .NETx.ToString()x.Clone()x.Equals(y)x.CompareTo(y)x.GetHashCode()
Eiffelx.outx.twinx.is_equal(y)When x isCOMPARABLE, one can simply dox< yWhen x isHASHABLE, one can usex.hash_codeWhen x isIDENTIFIED, one can usex.object_id
PHP$x->__toString()clone x[68]x== yspl_object_hash(x)
Perl"$x"[69]Data::Dumper->Dump([$x],['x'])[70]Storable::dclone($x)[71]Scalar::Util::refaddr($x )[72]
Raku~x[69]x.perlx.clonexeqv yxcmp yx.WHICH
Rubyx.to_sx.inspectx.dup or
x.clone
x== 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() orsprintf "%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

[edit]
Get object typeIs instance of (includes subtypes)UpcastingDowncasting
Runtime checkNo check
ABAP Objects[73]=?=
C++typeid(x)dynamic_cast<type *>(&x) !=nullptr[74]dynamic_cast<type*>(ptr)(type*) ptr or
static_cast<type*>(ptr)
C#x.GetType()xis type(type) x or xas type
Dtypeid(x)cast(type) x
Delphixis typexas type
eCx._classeClass_IsDerived(x._class, type)(type) x
Javax.getClass()xinstanceof class(type) x
Objective-C (Cocoa)[x class][75][x isKindOfClass:[class class]](type*) x
Swiftx.dynamicTypexis typexas! type
xas? type
JavaScriptx.constructor(If not rewritten.)xinstanceof class[76]
Visual Basic .NETx.GetType()TypeOf xIs type[74]CType(x,type) orTryCast(x,type)
XojoIntrospection.GetType(x)xIsA typeCType(x,type)
Eiffelx.generating_typeattached {TYPE} xattached {TYPE} xas down_x
Pythontype(x)isinstance(x,type)[76]
PHPget_class(x)xinstanceof class
Perlref(x)x->isa("class")
Rakux.WHATx.isa(class)[74]type(x) or
x.type
Rubyx.classx.instance_of?(type) or
x.kind_of?(type)
[76]
SmalltalkxclassxisKindOf: class
Windows PowerShellx.GetType()x-is [type][74][type]x or x-as [type]
OCaml[77](x:> type)
F#x.GetType()x:? type(x:?> type)
COBOLxAS type[74]

Namespace management

[edit]
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 nsimport *from nsimport item
PHPuse ns;use ns\item;
Perluse ns;use ns qw(item);
Raku
Ruby
Windows PowerShell
OCamlopen ns
F#
COBOL

Contracts

[edit]
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 end
f
do
ensure
tag: expression
end
f
do
check tag: expressionend
end
class X
invariant tag: expression
end
from 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

[edit]

Notes

[edit]
  1. ^parameter = argument may be repeated if the constructor has several parameters
  2. ^SAP reserved to himself the use of destruction
  3. ^abcdefghijklThis language usesgarbage 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. ^abcdefgThis language supportsmultiple 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 isNSObject for Cocoa and GNUstep, orObject otherwise.
  9. ^Usually the@interface portion is placed into aheader file, and the@interface portion is placed into a separate source code file.
  10. ^Prefixes to class and protocol names conventionally used as a kind of namespace
  11. ^In Python interfaces are classes which methods havepass as their bodies
  12. ^The class is an Object.
    Just send a message to the superclass (st-80) or the destination namespace (Visualworks).
  13. ^The namespace is an Object.
    Just send a message to the parent namespace.
  14. ^Afinalizer 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.
  15. ^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
  16. ^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 thedefault constructor is used.
  17. ^Any Eiffel procedure can be used as a creation procedure, aka constructors. See Eiffel paragraph atConstructor (computer science).
  18. ^Implementing{DISPOSABLE}.dispose ensures thatdispose will be called when object is garbage collected.
  19. ^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.
  20. ^This syntax is usually used tooverload constructors
  21. ^In JavaScript,constructor is an object.
  22. ^Constructors can be emulated with a factory method returning a class instance.
  23. ^abcScope 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
  24. ^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.
  25. ^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. Seefriend function andfriend class for more details.
  26. ^Just send a message to the class
    classaddInstVarName:field.classremoveInstVarName:field.
  27. ^abcdJust assign a value to it in a method
  28. ^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.
  29. ^All class data is 'private' because the COBOL standard does not specify any way to access it.
  30. ^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.
  31. ^In ABAP, the return parameter name is explicitly defined in the method signature within the class definition
  32. ^In C++, declaring and implementing methods is usually separate. Methods are declared in the class definition (which is usually included in aheader file) using the syntax
  33. ^Although the body of a methodcan 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 toinline methods that are included in the class declaration; so if a very shortone-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 atemplate class or method occurs, then all the code must be included with the declaration, because only with the code can the template be instantiated.
  34. ^abJust assign a function to it in a method
  35. ^Alternative implementation:
    defbar():doc="The bar property."deffget(self):returnself._bardeffset(self,value):self._bar=valuereturnlocals()bar=property(**bar())
  36. ^these examples need theClass::Accessor module installed
  37. ^abcAlthough Eiffel does not support overloading of operators, it can define operators
  38. ^PHP does not supportoperator overloading natively, but support can be added using the"operator" PECL package.
  39. ^The class must implement theArrayAccess interface.
  40. ^The class must overload '@{}' (array dereference) or subclass one of Tie::Array or Tie::StdArray to hook array operations
  41. ^abIn 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
  42. ^C++ doesn't have a "super" keyword, because multiple inheritance is possible, and so it may be ambiguous which base class is referenced. Instead, theBaseClassName::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]
  43. ^abcdefghiThe keyword here is not avalue, and it can only be used to access a method of the superclass.
  44. ^But be afraid, they have not the same value.
  45. ^only for Optional types
  46. ^abIn 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.
  47. ^"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.
  48. ^"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.
  49. ^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.
  50. ^In OCaml, an inheritance declaration ("inherit") can optionally be associated with a value, with the syntax "inheritparent_class «parameters»as super". Here "super" is the name given to the variable associated with this parent object. It can be named differently.
  51. ^However, if the ability to have an "optional" value in OCaml is needed, then wrap the value inside anoption type, which values areNone andSome x, which could be used to represent "null reference" and "non-null reference to an object" as in other languages.
  52. ^assuming that "x" and "y" are the objects (and not pointers). Can be customized by overloading the object's== operator
  53. ^Only accessible from within the class, since theclone() method inherited fromObject is protected, unless the class overrides the method and makes it public. If using theclone() inherited fromObject, the class must implement theCloneable interface to allow cloning.
  54. ^The class should implement the interfaceComparable for this method to be standardized.
  55. ^Implemented by the object'scopyWithZone: method
  56. ^compare: is the conventional name for the comparison method in Foundation classes. However, no formal protocol exists
  57. ^Only if object conforms to thePrintable protocol
  58. ^Only if object conforms to theDebugPrintable protocol
  59. ^Only if object conforms to theEquatable protocol
  60. ^Only if object conforms to theComparable protocol
  61. ^Only if object conforms to thehashValue protocol
  62. ^Can be customized by the object's__str__() method
  63. ^Can be customized by the object's__repr__() method
  64. ^Can be customized by the object's__copy__() method
  65. ^Can be customized by the object's__eq__() method
  66. ^Only in Python 2.x and before (removed in Python 3.0). Can be customized by the object's__cmp__() method
  67. ^Can be customized by the object's__hash__() method. Not all types are hashable (mutable types are usually not hashable)
  68. ^Can be customized by the object's__clone() method
  69. ^abCan be customized by overloading the object's string conversion operator
  70. ^This example requiresuseingData::Dumper
  71. ^This example requiresuseingStorable
  72. ^This example requiresuseingScalar::Util
  73. ^Run-time type information in ABAP can be gathered by using different description Classes like CL_ABAP_CLASSDESCR.
  74. ^abcdeUpcasting is implicit in this language. A subtype instance can be used where a supertype is needed.
  75. ^Only for non-class objects. Ifx is a class object,[x class] returns onlyx. The runtime methodobject_getClass(x) will return the class ofx for all objects.
  76. ^abcThis language is dynamically typed. Casting between types is unneeded.
  77. ^This language doesn't give run-time type information. It is unneeded because it is statically typed and downcasting is impossible.

References

[edit]
Retrieved from "https://en.wikipedia.org/w/index.php?title=Comparison_of_programming_languages_(object-oriented_programming)&oldid=1271665684"
Categories:
Hidden categories:

[8]ページ先頭

©2009-2025 Movatter.jp