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 Data Structures - Retired Getting There Class Review

Nataly Rifold
Nataly Rifold
12,432 Points

Why declare some variables outside the constructor and some in the constructor?

I can add variables to the class and not to the constructor, I don't understand how I know what to declare under the class. And why can't I create the author just in the constructor and use the get on that? It's public so It should have no problem with accessing it.

public class Treet { private String mAuther; private String mDescription; private Date mCreationDate;

public Treet(String author, String description, Date creationDate) { mAuther = author; mDescription = description; mCreationDate = creationDate; }

Adrian Grabowski
Adrian Grabowski
2,622 Points

I'm not sure if I understand your question. Those variables inside your class are called instance variables. In the constructor you assigning them values and not declaring them. If you declare another variable in the constructor it's gonna have a local scope and won't be visible outside of the constructor.

2 Answers

Sean M
Sean M
7,344 Points

It's just the format of coding. It needs to be implemented this way for java to understand what you're trying to accomplish

The constructor is simply a method that gets executed when you instantiate your class. Specifying what variables you want set in your constructor is required so Java knows what instance variables are set in the constructor and which are not. In this case all of our instance variables are set in the constructor so it just looks like we are duplicating code.

I know that TypeScript (and maybe a few other object-oriented languages) lets you declare instance variables inside of a constructor like this:

public Example(private String name, private number age) {
  //your code here...
}

But Java forces you to be more explicit.