Comparison of programming languages (object-oriented programming)
释义
Object construction and destruction
Class declaration
Class members Constructors and destructors Fields Methods Properties Manually implemented Automatically implemented Overloaded operators Standard operators Indexers Type casts
Member access
Member availability
Special variables
Special methods
Type manipulation
Namespace management
Contracts
See also
References and notes
{{cleanup|reason=This article's reference section contains many footnotes, but lists no external references or sources.|date=June 2013}}{{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]
C++ (STL)
class variable«(parameters)»; or class *variable = new class«(parameters)»;
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);
Perl 6
«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[4]
[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:
JavaScript
var variable = new class«(parameters)» or var variable = { «key1: value1«, key2: value2 ...»»}
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}}
C++ (STL)
class name« : public parentclasses[5]» { 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 }
class name« : «parentclass»«, protocols»» { members }
protocol name« : parentprotocols» { members }
Python
class name«(parentclasses[5])»: {{keypress>Tab}} members
[9]
__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[5]» members end
colspan=2 {{n/a}}
Perl
package name; «@ISA = qw(parentclasses[5]);» members 1;
package name; members
Perl 6
class name «is parentclass «is parentclass ...[5]»» «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» ...[5]»» 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
[10]
[11]
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;
package name; members
Scala
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>Tab}} members
interface name «inherits parentinterfaces» {{keypress>Tab}} members
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>Tab}} get {{keypress|Tab}}{{keypress|Tab}} instructions {{keypress|Tab}}{{keypress|Tab}} return value {{keypress|Tab}} set {{keypress|Tab}}{{keypress|Tab}} instructions
get bar «as type» {{keypress>Tab}} instructions {{keypress|Tab}} return value
set bar «as type» {{keypress>Tab}} instructions
ISLISP
colspan=3 {{n/a}}
Automatically implemented
read-write
read-only
write-only
ABAP Objects
colspan=3 {{n/a}}
C++ (STL)
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;
type operatorsymbol(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 }
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
[37]
Perl
[38]
Perl 6
«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 typo>.}}Item with get(index) = expression and set index value = expression
member this{{Not a typo>.}}Item with get(index) = expression
member this{{Not a typo>.}}Item with set index value = expression
COBOL
colspan=3 {{n/a}}
Cobra
pro[index «as type»] as type {{keypress>Tab}} get {{keypress|Tab}}{{keypress|Tab}} instructions {{keypress|Tab}}{{keypress|Tab}} return value {{keypress|Tab}} set {{keypress|Tab}}{{keypress|Tab}} instructions
get[index «as type»] as type {{keypress>Tab}} instructions {{keypress|Tab}} return value
set[index «as type»] as type {{keypress>Tab}} instructions
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][53]
[x isEqual:y]
[x compare:y][54]
x.hash
pointer to object can be converted into an integer ID
Swift
x.description[55]
x.debugDescription[56]
x == y[57]
x < y[58]
x.hashValue[59]
reflect(x).objectIdentifier!.uintValue()
Smalltalk
x displayString
x printString
x copy
x = y
x hash
x identityHash
Python
str(x)[60]
repr(x)[61]
copy.copy(x)[62]
x == y[63]
cmp(x, y)[64]
hash(x)[65]
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[66]
x == y
spl_object_hash(x)
Perl
"$x"[67]
Data::Dumper->Dump([$x],['x'])[68]
Storable::dclone($x)[69]
Scalar::Util::refaddr( $x )[70]
Perl 6
~x[67]
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}}[71]
=
?=
C++ (STL)
typeid(x)
dynamic_cast<type *>(&x) != NULL
rowspan=8 {{n/a}}[72]
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][73]
[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}}[74]
Visual Basic .NET
x.GetType()
TypeOf x Is type
{{n/a}}[72]
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}}[74]
PHP
get_class(x)
x instanceof class
Perl
ref(x)
x->isa("class")
Perl 6
x.WHAT
x.isa(class)
{{n/a}}[72]
type(x) or x.type
Ruby
x.class
x.instance_of?(type) or x.kind_of?(type)
colspan=3 rowspan=2 {{n/a}}[74]
Smalltalk
x class
x isKindOf: class
Windows PowerShell
x.GetType()
x -is [type]
{{n/a}}[72]
[type]x or x -as [type]
OCaml
colspan=2 {{n/a}}[75]
(x :> type)
colspan=2 {{n/a}}
F#
x.GetType()
x :? type
(x :?> type)
COBOL
colspan=2 {{n/a}}
x AS type[72]
colspan=2 {{n/a}}
Namespace management
Import namespace
Import item
qualified
unqualified
ABAP Objects
C++ (STL)
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);
Perl 6
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++ (STL)
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
Perl 6
PRE { condition }
POST { condition }
Ruby
colspan=5 rowspan=5 {{n/a}}
Windows PowerShell
OCaml
F#
COBOL
See also
Object-oriented programming
References and notes
1. ^parameter = argument may be repeated if the constructor has several parameters 2. ^SAP reserved to himself the use of destruction 3. ^1 2 3 4 5 6 7 8 9 10 11 This language uses garbage collection to release unused memory. 4. ^OCaml objects can be created directly without going through a class. 5. ^1 2 3 4 5 6 This language supports multiple inheritance. A class can have more than one parent class 6. ^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. 7. ^Usually the @interface portion is placed into a header file, and the @interface portion is placed into a separate source code file. 8. ^Prefixes to class and protocol names conventionally used as a kind of namespace 9. ^In Python interfaces are classes which methods have pass as their bodies 10. ^The class is an Object. Just send a message to the superclass (st-80) or the destination namespace (Visualworks). 11. ^The namespace is an Object. Just send a message to the parent namespace. 12. ^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. 13. ^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 14. ^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. 15. ^Any Eiffel procedure can be used as a creation procedure, aka constructors. See Eiffel paragraph at Constructor (computer science). 16. ^Implementing {DISPOSABLE}.dispose ensures that dispose will be called when object is garbage collected. 17. ^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. 18. ^This syntax is usually used to overload constructors 19. ^In JavaScript, constructor is an object. 20. ^Constructors can be emulated with a factory method returning a class instance. 21. ^1 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 22. ^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. 23. ^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. 24. ^Just send a message to the class 25. ^1 2 3 Just assign a value to it in a method 26. ^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. 27. ^All class data is 'private' because the COBOL standard does not specify any way to access it. 28. ^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. 29. ^In ABAP, the return parameter name is explicitly defined in the method signature within the class definition 30. ^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 31. ^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. 32. ^1 Just assign a function to it in a method 33. ^Alternative implementation: 34. ^these examples need the [https://metacpan.org/module/Class::Accessor Class::Accessor] module installed 35. ^1 2 Although Eiffel does not support overloading of operators, it can define operators 36. ^PHP does not support operator overloading natively, but support can be added using the "operator" PECL package. 37. ^The class must implement the ArrayAccess interface. 38. ^The class must overload '@{}' (array dereference) or subclass one of Tie::Array or Tie::StdArray to hook array operations 39. ^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 40. ^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. 41. ^1 2 3 4 5 6 7 8 The keyword here is not a value, and it can only be used to access a method of the superclass. 42. ^But be afraid, they have not the same value. 43. ^only for Optional types 44. ^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. 45. ^"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. 46. ^"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. 47. ^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. 48. ^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. 49. ^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. 50. ^assuming that "x" and "y" are the objects (and not a pointer). Can be customized by overloading the object's == operator 51. ^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. 52. ^The class should implement the interface Comparable for this method to be standardized. 53. ^Implemented by the object's copyWithZone: method 54. ^compare: is the conventional name for the comparison method in Foundation classes. However, no formal protocol exists 55. ^Only if object conforms to the Printable protocol 56. ^Only if object conforms to the DebugPrintable protocol 57. ^Only if object conforms to the Equatable protocol 58. ^Only if object conforms to the Comparable protocol 59. ^Only if object conforms to the hashValue protocol 60. ^Can be customized by the object's __str__() method 61. ^Can be customized by the object's __repr__() method 62. ^Can be customized by the object's __copy__() method 63. ^Can be customized by the object's __eq__() method 64. ^Only in Python 2.x and before (removed in Python 3.0). Can be customized by the object's __cmp__() method 65. ^Can be customized by the object's __hash__() method. Not all types are hashable (mutable types are usually not hashable) 66. ^Can be customized by the object's __clone() method 67. ^1 Can be customized by overloading the object's string conversion operator 68. ^This example requires useing Data::Dumper 69. ^This example requires useing Storable 70. ^This example requires useing Scalar::Util 71. ^Run-time type information in ABAP can be gathered by using different description Classes like CL_ABAP_CLASSDESCR. 72. ^1 2 3 4 Upcasting is implicit in this language. A subtype instance can be used where a supertype is needed. 73. ^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. 74. ^1 2 This language is dynamically typed. Casting between types is unneeded. 75. ^This language doesn't give run-time type information. It is unneeded because it is statically typed and downcasting is impossible.
3 : Programming language comparisons|Object-oriented programming|Object-oriented programming languages