In Java we can use "this" to self-reference an object. Is there an equivalent in Ada? Or do all parameters need to be passed explicitly?
-
3It's not a duplicate : the linked answer is specific to task objects; this question relates to objects in general. In lieu of being able to answer : you can name the first formal parameter in each of the object's methods `this` to achieve the usual effect. – Oct 06 '14 at 14:02
-
2To expand on this: In Ada, the object on which a method (subprogram) operates is an explicit parameter, usually the first parameter (it has to be the first parameter for you to use Obj.Operation notation). So you just use the parameter name. In Java and other languages, it's implicit, and you use `this` or `self` to refer to this implicit parameter. A lot of Ada code I've seen uses `this` or `self` as the name of the first parameter, but this is a style decision. – ajb Oct 06 '14 at 15:13
1 Answers
There isn't an equivalent in Ada, because the mechanism for defining operations of an object is different. In Java and most other well-known OO languages, the method definitions are part of the type (class) definition:
public class MyClass {
public String getName() { ... }
}
getName
is defined inside MyClass
, and therefore is an instance method that operates on a MyClass
object. In effect, the code for getName()
has an implicit parameter of type MyClass
, and within the body of getName()
, the keyword this
is used to refer to that implicit parameter. Some other languages use self
instead of this
.
Ada doesn't do things this way; you can't define a procedure
or function
inside the record type definition (although protected type definitions allow this). To define an operation on an object, the procedure
or function
is defined outside the record
type (or type extension) definition, with one of the parameters, usually the first (*), being the record type:
type My_Class is tagged record
...
end record;
function Get_Name (Obj : My_Class) return String;
-- note that this is outside the "record" .. "end record"
The explicit parameter is how Ada knows that this is an operation of My_Class
--there's no other way to tell it, since the function doesn't have to follow the record definition immediately. Since there's no implicit parameter, you just use the explicit parameter's name, Obj
, to refer to the object. Many Ada programmers use the names This
or Self
as the parameter name to make it look similar to other languages.
(*) A procedure or function can still be an operation of My_Class
, if any parameter has type My_Class
and it's defined in the same "declaration list" as the My_Class
type.
type My_Class is tagged record .. end record;
function Get_Something (N : Integer; Obj : My_Class) return String;
This is a primitive operation of My_Class
, and it is polymorphic (it can dispatch to overriding functions of derived types), but you can't say X.Get_Something(3)
because the My_Class
parameter isn't the first parameter.

- 31,309
- 3
- 58
- 84