What is a constructor and what is this keyword?

508 views

What is a constructor and what is this keyword?

In: Engineering

2 Answers

Anonymous 0 Comments

I’m gonna guess you’re using java, as it uses “this” keyword.

Constructor is a special method that gets called when you create an object. Say, you have class String. When you create new string using

String s = new String()

You notice that class String gets called as if it was a function. Well, it kinda is. In particular, the function that kinda gets called is called constructor of String. It is a little bit wonky since there is some magic that compiler/runtime does for you to get you this new object, pass arguments to constructor etc, but you can just think of constructor as your chance to do housekeeping so that before variable s gets assigned with this String object, you can set this object up in a way that it’s ready for use.

And when you do class methods, there is special keyword “this” that’s used to refer to the object itself. Say, you can define concatenation method. String takes another String as an argument, and returns new String that’s the combination of two. You’d have it be method “concatenate(String s)”

So you have this second String s to add to yourself, but… what are your own contents? Well, “this” is you. So it’s this.contents + s.contents.

I don’t remember Java syntax here for how “this” is handled, there are a couple of competing ways languages use to sell the conceptualization of “this”, functionally there is no difference but the flavor changes a bit from language to language.

Anonymous 0 Comments

what language are we talking about? Constructor as a keyword is in some languages to denote a constructor method, ie a method that is called when object is being instantiated.