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 Unit Testing in Java How to Test Fixtures

Florian Tönjes
.a{fill-rule:evenodd;}techdegree seal-36
Florian Tönjes
Full Stack JavaScript Techdegree Graduate 50,856 Points

Why not initialize the creditor field directly?

Why does it make sense to initialize the creditor field in the setUp method? Why not just initialize it where the field is being defined in the class?

I wonder about this in general. Why initialize a field in a constructor and not just directly at definition?

3 Answers

Hi Florian,

You can create many instances of a class. If you hard-code the value of the member variables, each instance will be identical. If, however, you all the constructor to set the values, the user can determine the state of the instance when the instance is created.

Take a car class:

public class Car {
  private String mColor;

  public Car(String color) {
    mColor = color

Here the user can set the colour of each instance of Car so we can create a customized instance suitable for our requirements. Otherwise, we'd have to have a RedCar class, a BlueCar class etc; that's not what object oriented programming is about. Like:

Car redCar = new Car("red");
Car blueCar = new Car("blue");

This uses one class template to create multiple instance of it, designed exactly how the user wants each instance to look. Obviously, real-world class can have more member variables to generate a greater degree of customization, but you see my point., hopefully.

Make sense?


Vince Campanale
Vince Campanale
5,263 Points

Good question - good answer.


please help me i did exactly the same for the code challenge that follow but can't pass can somebody help me please. the get help button of the code challenge is not is not working

Just wanted to add that to generate a method in IntelliJ IDEA 2016.2.4 you use CTRL-N on a Mac, not Command-N.

As of 2018 in my InteliJ IDEA Ultimate 2018.1 it's ⌘ N