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 Objects (Retired) Harnessing the Power of Objects Helper Methods and Conditionals

Aditya Sheode
Aditya Sheode
1,291 Points

static for every method

I am doing java objects whatever methods i create like load or isEmpty imma keep having to add the keyword static otherwise the class cant refrence to it help please?

4 Answers

Well if you want to call the method to the class directly you will need to provide the 'static' keyword.

If you do instantiate an object from that class you will not need to.

Static members belong to the class instead of a specific instance.

It means that only one instance of a static field exists even if you create a million instances of the class or you don't create any. It will be shared by all instances.

Since static methods also do not belong to a specific instance, they can't refer to instance members (how would you know which instance Hello class you want to refer to?). static members can only refer to static members. Instance members can, of course access static members.

For example if you create this

public class Car {
public static color red;
}

you can call the color directly in the class like

System.out.printline(Car.color);

if you remove the static keyword you need to create an object first and then call the variable:

Car myCar = new Car();
System.out.printline(myCar.color);
Aditya Sheode
Aditya Sheode
1,291 Points

public class CandyBar { public static final int MAX_CANDY = 12; private String mCharacterName; public static int mCandyCount;

public CandyBar(String characterName) {
  mCharacterName = characterName;
  mCandyCount = 0;
}

public static boolean isEmpty(){ return mCandyCount == 0; } public static void load() { mCandyCount = MAX_CANDY; }

public String getCharacterName() { return mCharacterName; } }

Chris Tvedt
Chris Tvedt
3,795 Points

You forgot to make an object, thats why you need the "static". you are missing

CandyBar candyBar = new CandyBar();

if you forget this, you will have to make the mCandyCount static to use it like this

System.out.printf("You have %s candy bars.\n", CandyBar.mCandyCount);

but if you make the object you dont have to make it static and you can do this:

System.out.printf("You have %s candy bars.\n", candyBar.mCandyCount);

Please someone correct me if i am wrong.

Aditya Sheode
Aditya Sheode
1,291 Points

no no youre correct i realised it later