+ 1

Why does a constructor have to run after we create an object of it? What is its purpose?

I understand that a constructor runs if we create its object; it is triggered by "new Person()" for example in "Person obj1 = new Person()" if I'm not mistaken. But what's the purpose? Can you give me an example--a simple illustration if there's any? I think that I'm going to get it after some further lessons, (I haven't finished my lesson yet in java) but it had been puzzling my mind and now hoping for an answer.

17th Jan 2018, 10:32 PM
Eric
Eric - avatar
3 odpowiedzi
+ 2
Let’s say you have a person and you want to give it a name, gender, age, anything else. Settings these attributes could be the job of a constructor: public class Person { public Person(int age, string name) { this.age = age; this.name = name; } public int getAge() { return age; } public string getName() { return name; } private int age; private string name; }; Now, we want to create a person: Person prs = new Person(3, “hi”); Now, we have a 3-year-old named hi. If I made any mistakes in that, I haven’t used Java in a while. In this example, you could just create methods to set the age and name, however for more complicated systems of superclasses and subclasses where a lot happens in the constructor, it could get confusing to need to call a bunch of other methods upon creating each object.
18th Jan 2018, 12:51 AM
Jacob Pembleton
Jacob Pembleton - avatar
0
Thanks for your answers! I really still got a long way to go and I hope I can truly learn and master java (my favorite programming language) here at sololearn and in other videos about it in the internet. :-)
18th Jan 2018, 2:07 PM
Eric
Eric - avatar