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

Andrada Terenche
Andrada Terenche
1,103 Points

Why do we declare private but still change characterName?

I don't understand why we declare private String characterName, but then use a constructor to be able to assign it a value? Doesn't that defeat the whole purpose of private type?

1 Answer

Thomas Nilsen
Thomas Nilsen
14,957 Points

The whole point of classes and variables being public, proctected, private, or package-private is that you can controll what people who use those classes, are allowed to do.

Even though a class has a private variable, we can still do what we want with it, inside that class

But once you do something like this:

class Person {
    private String name;

    Person(String name) {
        this.name = name;
    }
}

class Test {
    public static void main(String[] args) {
        Person person = new Person("Tammy");
        person.name; //This is NOT allowed since the variable is private
    }
}

If you just wanted to expose that variable, and not have people change it's value, you could just provide a public getter-

public String getName() {
        return name;
    }
Jennifer Nordell
seal-mask
.a{fill-rule:evenodd;}techdegree
Jennifer Nordell
Treehouse Teacher

In addition to Thomas' explanation (which was great by the way), I'd like to add that it may not be other people trying to change that code. It could be code that you coded yourself! We all make mistakes and it's easy to allow other bits of our code to change things around that shouldn't be changed in that place. :sparkles: