Can anyone help me to understand constructors? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Can anyone help me to understand constructors?

Please Explain what happens in the main method and clarify the purpose of using the keywords etc. in the given code: https://code.sololearn.com/cOtodLoXFoBB/?ref=app

7th Dec 2017, 7:11 AM
SaFFire1
SaFFire1 - avatar
1 Answer
+ 2
You create an instance of class Person and give "David" to the class constructor which receives "David" as parameter nm and which sets the name property of the instance to nm (effectively to "David" because it is evaluated). You save the instance into variable p. Then p.getName() is called. This calls the getName() method on the instance. It returns the name property as a variable (String) which evaluates to "David". Then this is printed out by the Console.WriteLine() function so "David" will appear as output. Note: constructors always run after instantiating (creating) an instance, so when executing new Person("something") the Person(nm) function (the constructor) will be executed.
7th Dec 2017, 9:41 AM
Wesley Stessens
Wesley Stessens - avatar