Single logo
  • Courses
  • Blog
  • About
Join on SkoolJoin on Skool

In this topic

Java
  • Install Java 25 (JDK) and IntelliJ IDEA, Then Run Your First Program
  • Use Claude Agent, Copilot or Junie Inside IntelliJ IDEA
  • Java Hello World with Maven: What the JDK Does and What Maven Adds
  • Java Variables, Keywords and Naming Rules
  • Maven in IntelliJ: pom.xml, Dependencies and the Build Lifecycle
  • Java Primitive Types and Memory: What int x = 5 Really Does
  • Java Strings and Text Blocks: Quotes, Concatenation and parseInt
  • Java Operators: Arithmetic, a++ vs ++a, Precedence, && || and the Ternary
  • Java Type Casting: Widening, Narrowing and Converting Text to Numbers
  • Java Practice Lab: A Cafe Bill with Variables, Operators and Casting
  • Java if, else and switch: Braces, Else-If Ladders and the Modern Switch
  • Java Loops: for, while, do-while and for-each
  • Java break, continue and Nested Loops
  • What's New in Java 21 to 25: Compact Source Files and Sequenced Collections
  • Java Arrays: Indexes, Default Values, Loops and 2D Grids
  • Java Methods and Overloading: Parameters, return and Pass-by-Value
  • Java Scope, Code Blocks and the Call Stack
  • Read User Input in Java with Scanner (and the Leftover Enter Trap)
  • Java Practice Lab: A Gym Weekly Tracker with Loops, Arrays and Methods
  • Debugging Java in IntelliJ: Stack Traces, Breakpoints and a Better AI Prompt
  • Java var: Let Java Infer the Type
  • Push and Pull in IntelliJ: Two Developers, One GitHub Repository, a Rejected Push and a Conflict
  • Java Classes and Objects: One Blueprint, Many Cars
  • Java Constructors and the this Keyword
  • Java Instance Methods, Getters, Setters and toString
  • Java static: Fields, Methods and Blocks Shared by the Whole Class
  • Java Packages and Imports: Every Class Has an Address
  • Java Access Modifiers and Encapsulation: Private Data, Public Methods
  • Java final and Immutable Objects: Assign Once, Share Safely
  • Java Strings as Objects: The String Pool, == vs equals, StringBuilder and printf
  • Java Practice Lab: A Library Book Catalogue with final Fields and StringBuilder
  • Java Inheritance: extends, super and the Order Objects Are Built
  • Java Method Overriding, @Override and the Object Class
  • Java Polymorphism: Upcasting, Dynamic Dispatch and Downcasting
  • Java Composition: Has-A vs Is-A
  • Java Abstract Classes: A Parent That Leaves One Blank
  • Java Interfaces: Contracts and Multiple Inheritance
  • Java Nested, Inner and Anonymous Classes
  • Java Enums with Fields, Methods and switch
  • Java Practice Lab: Payment Processing with an Interface, an Abstract Class and an Enum
  • Java Records: A Whole Data Class in One Line
  • Java Sealed Classes and Interfaces
  • Java Pattern Matching with instanceof and switch
  • Java Record Patterns: Unpacking a Record
  • Java equals and hashCode: Why a HashSet Needs Both
  • From Arrays to Collections: The Java Collections Framework Map
  • Java Wrapper Classes and Autoboxing
  • Java ArrayList: The Stretchy Array
  • Java LinkedList vs ArrayList: Nodes or an Array
  • Java Sets: HashSet, LinkedHashSet and TreeSet
  • Java Sorting with Comparable and Comparator
  • Java Maps: HashMap, LinkedHashMap and TreeMap
  • Java Stacks, Queues and Deques: ArrayDeque and PriorityQueue
  • Choosing a Java Collection: Immutable and Sequenced Collections
  • Java Exception Handling: try, catch and finally
  • Java throw, throws, Checked vs Unchecked and Custom Exceptions
  • Java try-with-resources and Clean Error Handling
  • Java Generics: Type-Safe Containers
  • Java Generic Methods, Bounded Types and Wildcards
  • Java Lambdas and Functional Interfaces
  • Java Built-in Functional Interfaces: Predicate, Function, Consumer, Supplier
  • Java Optional: Saying Maybe Without null
  • Java Streams I: filter, map and reduce
  • Java Streams II: Collectors, groupingBy and flatMap
  • Why Concurrency: Processes, Threads and the Main Thread in Java
  • Creating Threads in Java: Thread, Runnable and Lambdas
  • Java Thread Lifecycle: sleep, join and interrupt
  • Java Race Conditions and synchronized
  • Java volatile and Atomic Variables
  • Java ExecutorService and Thread Pools
  • Java Callable, Future and CompletableFuture
  • Java Locks, Deadlock and tryLock
  • Java Concurrent Collections and Virtual Threads
  • Why Slow Work Belongs off the Request Thread: 202 Accepted and a Job Id in Spring Boot
  • Virtual Threads in Spring Boot: One Property, and the Connection Pool Trap
  • @Async, Named TaskExecutors and Structured Concurrency in Spring Boot
  • Java Files and Directories with NIO.2: Path and Files
  • Reading and Writing Text Files in Java
  • Java Structured Data: Reading and Writing JSON and CSV
  1. Blog
  2. /
  3. Java
  4. /
  5. Object-Oriented Programming

Java Access Modifiers and Encapsulation: Private Data, Public Methods

A bank account keeps its balance private and lets money in only through deposit(), which refuses -200 so the balance ends at 650. A setter that refuses ages -4 and 250, and the four access levels side by side.

Chaand Sheikh

·27 November 2026·Updated 28 November 2026Object-Oriented Programming

What you will learn

  • Protect an object's data with private fields and public methods
  • Write a deposit method and a setter that refuse bad values
  • Compare the four access levels: private, package (no modifier), protected and public
  • Explain why a method is a better door than an open field

Before you start

  • Java instance methods, getters, setters and toString
  • Java packages and imports

A bank account has an owner and a balance, and no code outside should be able to change them directly. Encapsulation means keeping that data private and offering public methods as the only way in. A method can check what comes in; an open field can't.

The Account object keeps owner and balance private inside a wall. savings.balance = -5000 is blocked by the compiler. deposit(-200) goes through the deposit door, fails the check and is rejected; the balance stays 500. deposit(150) passes the check and the balance becomes 650. Account (private data) owner = "Priya" balance = 500 → 650 deposit deposit(150) deposit(-200) savings.balance = -5000 check passes rejected blocked: private access
The data is private; the only way in is a method that checks first.

Private data, a door that checks

package org.studyeasy.s03l06;

public class Account {
    private String owner;       // only Account's code can use these
    private double balance;

    public Account(String owner) {
        this.owner = owner;
    }

    public double getBalance() {    // others may read it
        return balance;
    }

    public void deposit(double amount) {
        if (amount <= 0) {          // check before changing
            System.out.println("Rejected deposit: " + amount);
            return;
        }
        balance = balance + amount;
    }
}

private means only code inside Account can use owner and balance. getBalance() is public, so other classes can read the balance but can't set it. deposit is the only way to change it, and it refuses anything zero or below.

Why a method rather than an open field? A method can hold logic. It can validate the amount, or check that a user is logged in before it hands anything back. An open variable does whatever anyone writes into it.

package org.studyeasy.s03l06;

public class Ex01_Deposit {
    public static void main(String[] args) {
        Account savings = new Account("Priya");
        savings.deposit(500.0);
        savings.deposit(-200.0);        // refused by deposit()
        savings.deposit(150.0);
        System.out.println("Balance: " + savings.getBalance());
    }
}
Rejected deposit: -200.0
Balance: 650.0

All three deposits go through the method, and the account decides what's allowed: 500 + 150 = 650. Write savings.balance = -5000; here and javac says balance has private access in Account.

A setter that says no

package org.studyeasy.s03l06;

public class Customer {
    private String name;
    private int age;

    public Customer(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    // A setter that checks: a bad age never reaches the field
    public void setAge(int age) {
        if (age < 0 || age > 120) {
            System.out.println(name + ": invalid age " + age);
            return;
        }
        this.age = age;
    }
}
package org.studyeasy.s03l06;

public class Ex02_ValidatedSetter {
    public static void main(String[] args) {
        Customer priya = new Customer("Priya");
        priya.setAge(29);
        priya.setAge(-4);           // rejected: age stays 29
        priya.setAge(250);          // rejected too
        System.out.println("Priya's age: " + priya.getAge());
    }
}
Priya: invalid age -4
Priya: invalid age 250
Priya's age: 29

29 passes and is stored. -4 and 250 fail the check, so the old value stays. The field only ever holds proper values. This is the reason behind the plain getters and setters you saw earlier: they're the place where checks like this go.

Who can see it: the four levels

ModifierSame classSame packageChild classesEverywhere
privateyesnonono
(no modifier)yesyesnono
protectedyesyesyesno
publicyesyesyesyes

Child classes come with inheritance, so the protected row will make more sense later. A good habit: start every field as private and open up only what others really need.

Recap

  • Fields private, methods public.
  • Every change goes through a method that checks first, so nobody can put the object in a bad state.
  • Reaching a private field from outside is a compile error: "has private access".
  • Pick the access level by who really needs it, from private up to public.

Try it yourself: add a withdraw method to Account that refuses amounts of zero or less and amounts larger than the balance.

Keep going in Java · 28 of 79

Previous
Java Packages and Imports: Every Class Has an Address
Next post
Java final and Immutable Objects: Assign Once, Share Safely
Community · Free to join
Single logo

StudyEasy AI Community

Hosted onSkool

Learn AI engineering, share what you build, and connect with other learners.

  • Free resources: lesson files, notebooks and code

  • Ask questions and join engineering discussions

  • Meet real people learning and building with AI

Join free on Skool

Related course on Udemy

FULL STACK JAVA : JAVA + JSP + SPRING BOOT AI + REACT + VIBE

Java 25, JSP, Hibernate, Spring Boot 4, REST APIs, React and Spring AI.View on Udemy ↗: FULL STACK JAVA : JAVA + JSP + SPRING BOOT AI + REACT + VIBE (paid course, opens in a new tab)

Related posts

Java Classes and Objects: One Blueprint, Many Cars

Six loose variables for two cars doesn't scale. A Car class is the blueprint; new builds each car with its own brand, speed and fuel. Plus field defaults, and why two variables can point at one car.

Java Constructors and the this Keyword

A constructor decides how an object is born: new Car("Toyota", 42.5) arrives filled in. this.brand vs brand, a second constructor that calls this(brand, 50.0), and why new Car() stops compiling once you write your own.

Java Instance Methods, Getters, Setters and toString

Give a Car class behaviour: accelerate() changes only this car's speed, private fields are reached through getSpeed and setSpeed, and toString turns Car@1b6d3586 into 'Toyota doing 60 km/h'.

Java static: Fields, Methods and Blocks Shared by the Whole Class

A static field lives once on the class: every Car ticks the same carsBuilt counter while keeping its own brand. Static methods need no object, a static block runs before main, and main is static so the JVM can start with no object.

On this page

  • Private data, a door that checks
  • A setter that says no
  • Who can see it: the four levels
  • Recap
Community · Free to join
Single logo

StudyEasy AI Community

Hosted onSkool

Learn AI engineering, share what you build, and connect with other learners.

  • Free resources: lesson files, notebooks and code

  • Ask questions and join engineering discussions

  • Meet real people learning and building with AI

Join free on Skool

Related course on Udemy

FULL STACK JAVA : JAVA + JSP + SPRING BOOT AI + REACT + VIBE

Java 25, JSP, Hibernate, Spring Boot 4, REST APIs, React and Spring AI.View on Udemy ↗: FULL STACK JAVA : JAVA + JSP + SPRING BOOT AI + REACT + VIBE (paid course, opens in a new tab)

Single logo

Empowering Education, One Course at a Time

About
About usContact us
Legal
Terms of UsePrivacy Policy

© 2026 StudyEasy Organization. All rights reserved.