Task 1 of 7 · 0 solved · 7 to go0%
You can read the problem, but answers are checked only for signed-in students. Sign in to answer →

4.4 Encapsulation — private fields

Lesson

Hiding the data

Marking a field private means only code inside the same class can touch it — from outside, object.field is not allowed. Bundling data together with the methods that manage it, and hiding the raw fields, is called encapsulation. Outside code then goes through methods instead of poking fields directly.


Worked example

class Person {
    private String name;              // hidden from outside

    String getName() { return name; }
    void setName(String n) { name = n; }
}

Person p = new Person();
p.setName("Rex");                     // OK: goes through a method
System.out.println(p.getName());     // Rex
// p.name = "Rex";   // NOT allowed: name is private

▶ Try it: name is private, so we use setName and getName. Run this, then change the name. (Writing p.name directly would not compile.)



What does making a field private do?


If name is private, which is allowed from outside the class?


Match each term to its meaning.


True or false?


Type exactly what this program prints.

class Box {
    private int size;
    void setSize(int s) {
        size = s;
    }
    int getSize() {
        return size;
    }
}

public class Main {
    public static void main(String[] args) {
        Box b = new Box();
        b.setSize(7);
        System.out.println(b.getSize());
    }
}