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

I am learning the lesson Java objects and I am not sure why my code isn't working. Please help. Example.java

public class Example {

public static void main(String[] args) {
    // Your amazing code goes here...
System.out.println("We are making a new Pez Dispenser.");
PezDispenser dispenser = new PezDispenser();
System.out.printf("The dispenser character is %s\n", dispenser.mCharacterName);    
}

}

PezDispenser.java

public class PezDispenser {

public static void main(String[] args) { public String mCharacterName = "Jedi";

} }

1 Answer

I don't remember the class, and you didn't give a link, so here's my best guess:

First, when you create a new PezDispenser you need to give the dispenser a name, as an actual parameter for the call to the PezDispenser constructor

public class Example {

    public static void main(String[] args) {
        // Your amazing code goes here...
        System.out.println("We are making a new Pez Dispenser.");
        PezDispenser dispenser = new PezDispenser("Jedi");  //requires a name as the parameter
        System.out.printf("The dispenser character is %s\n", dispenser.mCharacterName);    
    }
}

Second, you don't want to have a static main method in this class. This class is the "blueprint" for PezDispenser objects.

You do need an instance variable mCharacterName, and you need a constructor that will take a passed in name, e.g., "Jedi", and store it in the instance variable:

public class PezDispenser {
    String mCharacterName;

    public PezDispenser(String characterName) { 
        mCharacterName = characterName;
    } 
}

So now, when you call the constructor in Example: PezDispenser dispenser = new PezDispenser("Jedi"); , you pass in a name, and the constructor takes it and stores it in the mCharacterName variable in the dispenser object.