简体   繁体   中英

Self-Referencing in Ada that is similar to Java “this”?

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM