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

Jack C.
Jack C.
4,008 Points

What's the difference between initializing field inside vs outside constructor?

Class Test {

int number = 1;

vs.

int number; public Test() { number = 1; }

}

1 Answer

logically both are the same. But usually we initialize fields in the constructor by passing arguments to the constructor during the construction of object

For example:

 Class Test {
  int number ; // when not assign anything, then default value is 0

  public Test( int number) {
     this.number = number; // this refers to the current object
  }
}

// in the main method
Test testObject = new Test(1);