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
Roope Jourio
7,308 PointsCan someone ELI5 to me what is class constructor in Java, I don't get it!
Explain like I'm 5.
Why do you have to create class constructors, and what does it do?
To be more specific, why do I have to do this:
public class Treet {
private String mAuthor;
private String mDescription;
private Date mCreationDate;
public Treet(String author, String description, Date creationdate) {
mAuthor = author; // wtf?
mDescription = description; // wtf?
mCreationDate = creationdate; // wtf?
}
public String getAuthor() {
return mAuthor; // why do we return this? We just set mAuthor = author. Couldn't we just use that instead of this mValue?
}
public String getDescription() {
return mDescription;
}
public Date getCreationDate() {
return mCreationDate;
}
}
1 Answer
Ivan Bagaric
Courses Plus Student 12,356 PointsWhen you initialize your class or object, constructor is first function which get called!
so for example
Treet t1 = new Treet('Some value', 'Value', 123); Treet t2 = new Treet('New Author', 'New treet', 456);
and when you want get author of treet 2 you gonna do t2.getAuthor();
And that return mAuthor; means you asking for value and this will RETURN it to you, if you later on change mAuthor variable in that class, you can return it again with this function.
that is just short explanation if you got it