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 trialKurt Daisley
4,228 Points"A constructor is a method that will run when you instantiate the class."
At about 00:39, Chris makes the above statement: a constructor is a method ....
So, is a constructor just a type of method that doesn't return a type, or is it something completely different from a method?
3 Answers
Timothy Hilley
2,292 PointsA 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 {
//}
Bartosz Piechaczek
1,876 PointsThe constructor is a method. It runs when you create a class instance. It has no return type. The name must be the same as a class name.
If you still don't understand what is it just tell me. I'll try to explain it in other words.
Have a nice day!
Kurt Daisley
4,228 PointsThanks so much, Bartosz! That does help.
Muthembwa Victor
431 PointsWhat does he mean by saying instance