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 Objects Meet Objects Constructors

mohamadreza azadi
mohamadreza azadi
5,167 Points

why constructor is same name in our field?

i'm so confused about this subject why we put it on constructor argument same name in our field ?????? please help me

2 Answers

Every class has a constructor which is named the same as the class. You specify what is required to instantiate(create a object of that class) in the constructor. In this example, in order to create a PezDispenser object, you will have to pass the characterName value as specified in the the PezDispenser's constructor. For example, this is how you would create a PezDispenser object when you add the characterName value into the constructor:

PezDispenser newDispenser = PezDispenser("DarthVader");

If you left the constructor without characterName, you would create the object like this:

PezDispenser newDispenser = PezDispenser();

A constructor is the main attributes of the object that creates an object from the template. Look at a class as a play-dough mold, and the variables it takes in is the play-dough, creating an object (the instance). Without the constructor, instances cant be made. The class itself is not an object, but a blueprint on making that object. the instances are the objects. So in other classes, i can make as many playdough molds as i please and use them separately as seperate objects of the same class, because of the constructor.

public class PlayDoughStar {

private String starColor;

public PlayDoughStar(String starColor) {
     this.starColor= starColor;
} 
//the rest of the class code
}

so in a different class, i want to make a play-dough star:

public class Table {
PlayDoughStar redStar = new PlaydoughStar("red");
PlayDoughStar blueStar = new PlaydoughStar("blue");
//Tables constructor here {
//}