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 Meet Objects Constructors

Jun Dong
Jun Dong
4,754 Points

Where was the value Yoda for the String characterName passed in?

class PezDispenser { private String characterName;

public PezDispenser(String characterName) { this.characterName = characterName; }

public String getCharacterName(){ return characterName; } }

Please help i don't understand, where was the value Yoda for the String characterName passed in???

PezDispenser dispenser = new PezDispenser("Yoda");

I don't understand how this works, why didn't he do String characterName = "Yoda";?

2 Answers

Gergely Horvath
PLUS
Gergely Horvath
Courses Plus Student 8,207 Points

This is how constructors work. Given your code above, when you instantiate PezDispenser, the constructor is automatically run. So for example in an other class, or in your main method, when you need a PezDispenser, you write:

PezDispenser  pezDispenser = new PezDispenser ("Yoda");

This is because the constructor method expects a string in its signature.

Jun Dong
Jun Dong
4,754 Points

What if there's multiple strings?

Gergely Horvath
PLUS
Gergely Horvath
Courses Plus Student 8,207 Points

You can initialize multiple variables in your constructor like this:

public class NewClass {
    private final int i;
    private final int j;
    private final char c;
    private final String s;

    public NewClass(int i, int j, char c, String s) {
        this.i = i;
        this.j = j;
        this.c = c;
        this.s = s;
    }
}

and you instantiate it like this:

NewClass nc = new NewClass(1, 2, 'c', "string");
Jun Dong
Jun Dong
4,754 Points

Thank you so much there's a lot of things he say that confuses me so thanks you