Search the courses, subjects, tracks, games and features, or jump straight to a page.
Learn it your way
A short class with Sarah and her students. The other ways are under More.
Sign up free to listen. Transcripts are free to read.
Last time we saw that public opens a member to every class. Today we go to the other end: private. Where do you think a private field can be used?
Only inside the same package?
That would be default access. Private is narrower still: only code written inside the same class can use it, not even its neighbours in the package.
So if my Main class writes s.marks = 95 and marks is private, the program will not run?
It will not even compile. The compiler stops with the message 'marks has private access in Student'. Private is checked before the program runs.
Then how does Main ever find out the marks?
Through a door the class chooses to open, such as a public method getMarks(). Think of a locker: only you hold the key, but you can choose to show what is inside.
Why not make every field public and save ourselves some typing?
Because someone could set the marks to minus fifty?
Exactly. If marks is private, every change has to go through setMarks, and setMarks can check that the value lies between 0 and 100.
So the setter is like a security guard at the gate.
A good picture. The getter lets others read, the setter lets them change, and the checks inside keep the object valid. We call this encapsulation, or data hiding.
Can a method be private too?
Yes. A private helper such as total() can do an inner step for a public average() method, and no outside class can call it directly.
A puzzle: why can't we write new Math() in Java?
Because Math only has static methods, so it needs no objects?
That is why it needs none, and a private constructor is how Java enforces it. No other class can call a private constructor.
Can a subclass use its parent's private fields?
No. The subclass must use the parent's public or protected methods. Try it and you get 'balance has private access in Account'.
And can one Student object read another Student's private marks?
Yes, as long as that code is written inside the Student class. Privacy belongs to the class, not to each separate object.
A private member can be used only inside the class that declares it, whatever the package.
Private fields with public getters and setters let a class check every change to its data.
Private methods carry out internal steps that other classes should not call or depend on.
They stop outside code from creating objects, as in utility classes such as Math.
Top-level classes cannot be private, and subclasses cannot use a parent's private members directly.
A setter that refuses invalid marks keeps a private field valid:
class Student {
private String name;
private int marks;
Student(String name) {
this.name = name;
}
public void setMarks(int m) {
if (m >= 0 && m <= 100) {
marks = m;
} else {
System.out.println("Invalid marks " + m + " for " + name + "; value not changed.");
}
}
public int getMarks() {
return marks;
}
}
public class MarksDemo {
public static void main(String[] args) {
Student s = new Student("Arjun");
s.setMarks(88);
s.setMarks(140);
System.out.println("Marks stored: " + s.getMarks());
}
}A private helper method does the adding up for a public average method:
class ReportCard {
private int[] scores;
ReportCard(int[] scores) {
this.scores = scores;
}
private int total() {
int sum = 0;
for (int i = 0; i < scores.length; i++) {
sum = sum + scores[i];
}
return sum;
}
public double average() {
return (double) total() / scores.length;
}
}
public class HelperDemo {
public static void main(String[] args) {
int[] marks = {72, 85, 90, 64, 79};
ReportCard card = new ReportCard(marks);
System.out.println("Average: " + card.average());
// card.total(); // error: total() has private access in ReportCard
}
}Code inside a class may read the private fields of another object of the same class:
class Box {
private int length;
private int width;
private int height;
Box(int l, int w, int h) {
length = l;
width = w;
height = h;
}
int volume() {
return length * width * height;
}
boolean isBiggerThan(Box other) {
// other.length is private, but this code is inside class Box, so it is allowed
return volume() > other.length * other.width * other.height;
}
}
public class SameClassDemo {
public static void main(String[] args) {
Box a = new Box(4, 3, 2);
Box b = new Box(2, 2, 5);
System.out.println("a is bigger than b: " + a.isBiggerThan(b));
}
}Private stays inside the class, no other code is let to pass.
Picture a bank whose vault has no outside door. Customers can only use the counter, where the cashier checks every request before touching the money. The vault is the private field; the counter is the public method.
Private Means Mine: only my own class may use what I mark private.
G.S.V. - Getter reads, Setter changes, Validation guards the data.
Term
Who can use a private member?
Click to flip
Term
Can a top-level class be declared private?
Click to flip
Term
Getter and setter
Click to flip
Term
Why does new Math() fail to compile?
Click to flip
Term
Can a subclass read its parent's private field directly?
Click to flip
A keyword (public, protected or private), or the lack of one (default), that decides which code may use a class or member.
The access level that limits a field, method, constructor or nested class to the class in which it is declared.
Keeping a class's data together with the methods that work on it, and hiding the data so that it can be changed only through those methods.
A public method that returns the value of a private field, such as getBalance().
A public method that changes a private field, usually after checking that the new value is valid.
A private method that carries out an internal step for other methods of the same class.
A constructor that only the class itself can call, used to stop other classes from creating objects.
private is Java's most restrictive access modifier: a private field, method or constructor can be used only by code inside the class that declares it, which is how a class hides its data and keeps it valid.
This lesson looks closely at the private access level. You will see exactly where a private member can be used (only inside its own class, whatever package or subclass is asking), why fields are usually made private and reached through public getter and setter methods, how private helper methods and private constructors are used, and which errors the compiler gives when code breaks these rules. Short, complete programs show each idea at work.
Java has four access levels: public, protected, default (package-private) and private. Private is the narrowest. A member declared private can be used only by code written inside the same class. Classes in the same package cannot use it, subclasses cannot use it, and classes in other packages cannot use it either.
The rule is checked by the compiler, before the program ever runs. If another class writes s.marks = 95; and marks is private in class Student, compilation stops with the message marks has private access in Student.
A top-level class cannot be private. Writing private class Shop at the top of a file gives the error modifier private not allowed here, because a top-level class can only be public or have default access.
The most common use of private is for fields. The class keeps its data private and offers public methods to read it (getters) and to change it (setters). Because every change has to pass through the class's own methods, the class can check each value first. This idea is called encapsulation or data hiding.
class BankAccount {
private String holder;
private double balance;
BankAccount(String holder, double openingAmount) {
this.holder = holder;
if (openingAmount > 0) {
balance = openingAmount;
}
}
public void deposit(double amount) {
if (amount > 0) {
balance = balance + amount;
} else {
System.out.println("Deposit refused: amount must be positive.");
}
}
public void withdraw(double amount) {
if (amount > 0 && amount <= balance) {
balance = balance - amount;
} else {
System.out.println("Withdrawal of " + amount + " refused.");
}
}
public double getBalance() {
return balance;
}
public String getHolder() {
return holder;
}
}
public class PrivateDemo {
public static void main(String[] args) {
BankAccount acc = new BankAccount("Riya", 1000);
acc.deposit(500);
acc.withdraw(2000);
acc.withdraw(300);
System.out.println(acc.getHolder() + " has " + acc.getBalance());
// acc.balance = -5000; // error: balance has private access in BankAccount
}
}The program prints Withdrawal of 2000.0 refused. and then Riya has 1200.0. No outside code can set the balance to a negative number, because the only way in is through deposit and withdraw, and both check the amount.
A private method does an internal step for the class, such as adding up marks before a public average() method divides the total. Other classes should not depend on such steps, so they are hidden.
A private constructor means no other class can create objects of the class. This suits a class that holds only static utility methods. Java's own Math class is built this way, which is why new Math() does not compile.
final class Converter {
private Converter() {
// no objects are needed: every method is static
}
static double cmToInch(double cm) {
return cm / 2.54;
}
}
public class UtilityDemo {
public static void main(String[] args) {
System.out.println("12.7 cm = " + Converter.cmToInch(12.7) + " inches");
// Converter c = new Converter(); // error: Converter() has private access in Converter
}
}BankAccount may read the private balance of another BankAccount object passed to it.Savings extends Account, code in Savings cannot touch Account's private balance; the compiler reports balance has private access in Account. The subclass must go through the parent's public (or protected) methods.Packages group related classes, and the access levels form circles, each inside the next: private (one class) sits inside default (one package), which sits inside protected (the package plus subclasses elsewhere), which sits inside public (everyone). Choosing private for a field is the safest starting point: open a member wider only when another class genuinely needs it.