Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

Java Unit Testing in Java How to Test Fixtures

Florian Tönjes
seal-mask
.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?

Steve.

Vince Campanale
Vince Campanale
5,263 Points

Good question - good answer.

:+1:

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