Skip to lesson

private fields and public methods

An access modifier is the word in front of a field, method or constructor that says which code may use it. An encapsulated class keeps its fields private and offers public methods.

Access levels on fields and methods

An access modifier is a keyword (private, protected or public, or no keyword for default access) written before a class, field, method or constructor. It decides which other code is allowed to use that member.

One line in main wipes Priya's account name. The cause is default access: a field with no access word is open to every class in the same package, as in Access modifiers (opens in a new tab).

Example 1 · No keyword means open to the whole package

DefaultDemo.javaJava
class Account {    String holder;    private int balance;
    public Account(String holder, int balance) {        this.holder = holder;        this.balance = balance;    }
    public void show() {        System.out.println(holder + ": Rs. " + balance);    }}
public class DefaultDemo {    public static void main(String[] args) {        Account a = new Account("Priya", 2500);        a.holder = "";   // compiles: same package        // a.balance = 0; would not compile        a.show();    }}
Output
: Rs. 2500

What this code does

  • holder has no access word, so main (same package) can overwrite it with an empty name.
  • balance is private, so the same kind of line for it would be a compile error. Forgetting private leaves a field open.

From most closed to most open: private (same class only), default (same package), protected (same package plus child classes, covered in extends (opens in a new tab)) and public (any class). All classes in one .java file share a package, so a field without private is fully open to main.

The usual pattern: private fields, public methods

Fields are the inside of an object: how it stores its data. Public methods are the outside: the menu of things other code may ask for.

Java
class Student {    private String name;    private int marks;
    public Student(String name, int marks) {        this.name = name;        this.marks = marks;    }
    public String getName() { return name; }
    public boolean scoredMoreThan(Student other) {        return marks > other.marks;    }}

Start with private for everything, and open a method only when outside code really needs it. The smaller the public menu, the fewer ways an object can be misused.

private belongs to the class, not to the object

scoredMoreThan(Student other) reads other.marks, another object's private field, and it compiles. Java checks access by where the code is written, not by which object it touches.

Example 2 · One Student reads another Student’s private field

CompareDemo.javaJava
class Student {    private String name;    private int marks;
    public Student(String name, int marks) {        this.name = name;        this.marks = marks;    }
    public boolean scoredMoreThan(Student other) {        return this.marks > other.marks;    }
    public String getName() {        return name;    }}
public class CompareDemo {    public static void main(String[] args) {        Student p = new Student("Priya", 91);        Student a = new Student("Arjun", 84);        if (p.scoredMoreThan(a)) {            System.out.println(p.getName() + " scored more than " + a.getName());        }    }}
Output
Priya scored more than Arjun

What this code does

  • other.marks is another object’s private field, but the code is inside Student, so Java allows it.
  • main still cannot write a.marks. Access depends on where the code is written.

This is safe: the code is part of the same class, written with the same rules. Code in any other class still gets a compile error, and that includes main in a separate demo class.

private helper methods

A helper method is a small method that does one step of the work for other methods of the same class. It is usually private, because outside code does not need it.

An ATM card checks the PIN before every withdrawal. A helper method does one small step like that for the class; make it private when only the class needs it.

Example 3 · A private helper inside an ATM card

AtmDemo.javaJava
class AtmCard {    private int pin;    private int balance;
    public AtmCard(int pin, int balance) {        this.pin = pin;        this.balance = balance;    }
    private boolean isCorrectPin(int enteredPin) {        return enteredPin == pin;    }
    public void withdraw(int enteredPin, int amount) {        if (!isCorrectPin(enteredPin)) {            System.out.println("Wrong PIN");            return;        }        balance = balance - amount;        System.out.println("Take Rs. " + amount + ", left Rs. " + balance);    }}
public class AtmDemo {    public static void main(String[] args) {        AtmCard card = new AtmCard(4321, 5000);        card.withdraw(1111, 500);        card.withdraw(4321, 500);    }}
Output
Wrong PIN
Take Rs. 500, left Rs. 4500

What this code does

  • isCorrectPin is one small step that only withdraw needs, so it is private.
  • The public menu has just one method, withdraw. The PIN and the helper stay inside.

Example 4 · Calling the private helper from outside

GuessDemo.javaJava
class AtmCard {    private int pin = 4321;
    private boolean isCorrectPin(int enteredPin) {        return enteredPin == pin;    }}
public class GuessDemo {    public static void main(String[] args) {        AtmCard card = new AtmCard();        System.out.println(card.isCorrectPin(1234));    }}
Sample compiler output
GuessDemo.java:12: error: isCorrectPin(int) has private access in AtmCard
        System.out.println(card.isCorrectPin(1234));
                               ^
1 error

What this code does

  • Private methods follow the same rule as private fields: only code inside AtmCard may call them.
  • Without this, any code could try PINs one by one, without going through withdraw.

Outside code cannot call a private helper, so you can change, rename or remove it later without breaking anyone.

private constructors

A plan costs Rs. 10 a day, and outside code should not choose its own price. Make the two-value constructor private: only code inside the class, such as another constructor calling this(...), can use it.

Example 5 · A private constructor called with this(...)

PlanDemo.javaJava
class Plan {    private int days;    private int price;
    public Plan(int days) {        this(days, days * 10);   // always Rs. 10 a day    }
    private Plan(int days, int price) {        this.days = days;        this.price = price;    }
    public void show() {        System.out.println(days + " days: Rs. " + price);    }}
public class PlanDemo {    public static void main(String[] args) {        new Plan(28).show();        new Plan(84).show();        // new Plan(28, 1) would not compile    }}
Output
28 days: Rs. 280
84 days: Rs. 840

What this code does

  • The two-value constructor would accept any price, so it is private. Only the class’s own code may call it.
  • Outside code must use Plan(int days), which always works out the right price.

From outside, new Plan(28, 1) fails with constructor Plan in class Plan cannot be applied to given types, and the reason line says Plan(int,int) has private access in Plan. this(...) is the call you met in Constructor chaining (opens in a new tab); Static methods (opens in a new tab) shows another common use of a private constructor.

Find the bug

Find the access bug

Select the line that is wrong.

main should take Rs. 5000 off the fees due.

Round 1 of 4

Next step

Check your understanding

12 quick questions