Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Java

Java constructors?

Hello,

I do not quite understand why we use constructors and what they do. I have watched the video on this topic but still need some help getting my head around them.

Thanks!

1 Answer

Constructors are used to initialize objects.

By default every class has a default constructor with no arguments. No fields can be initialized using a default constructor

Suppose you have a Student class

class Student {
      String firstName;
      String lastName;
}

Student tempStudent = new Student();

When tempStudent object is created a default constructor is used internally.

Now what if you want to create a new object call tempStudent2 with firstName as Allen and lastName as Outlaw. One way to do is to create the object similar to tempStudent and then set the fileds firstName and lastName. But the better way is to initialize the fields with the values while creating itself. In this case , we can define the constructors with the parameters. In below examples a constructors is defined with two String parameters.

Student(String first,String last) {
     firstName= first;
     lastName = last;
}

Student tempStudent1 = new Student("Allen","Outlaw");

Above method is a constructor. Notice, the name of constructor is same as the name of the class. Now tempStudent1 is created by required values.

This blog explains better blog .Feel free to skip the advanced concepts in this blog,