I am learning Delphi reading Marco Cantu's book and it's super complete. It's very clear but I have a doubt about the keyword self
. I already have experience with OOP and I have the basics of it. My question is very simple. Can I compare the keyword self (Delphi) to the keyword this (Java)?
When I read on the book about the self
used inside record, I got in my mind something like self : Delphi = this : Java
. Look at the code I created to make a test:
type
TMarioKart = packed record
Character: String;
Kart: String;
Tires: String;
Speed: double;
Competitive: boolean;
private
air-speed: integer;
ground-speed: integer;
water-speed: integer;
public
constructor Create(Character: string);
function ShowStats(a: TMarioKart):string; overload;
function ShowStats(a: TMarioKart; b: TMarioKart): string; overload;
end;
I am going to cut off the biggest part of the code, I am just showing the constructor here:
constructor TMarioKart.Create(Character: string);
begin
self.Character := Character;
end;
Using the keyword self
here I am referring to the Character of the record, and not to the Character passed in the method. Is this the correct way to use the self? Could it be the brother of Java's this
?
In every method, Delphi declares the Self variable as a hidden parameter. In a method, the value of the Self variable is the object reference. In a class method, Self is the class reference.
The self variable is used to represent the instance of the class which is often used in object-oriented programming. It works as a reference to the object. Python uses the self parameter to refer to instance attributes and methods of the class.
self is used in Objective-C classes to represent a pointer the current instance. this is used in C++ classes to represent a pointer the current instance. They perform analogous roles but on entirely different structures.
To refer to the current instance of a class, use the this keyword. The this keyword provides a way to refer to the specific instance in which the code is currently executing. It is particularly useful for passing information about the currently executing instance.
Yes, Delphi's Self
is the direct analogue of Java's this
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With