Encapsulation
Encapsulation means keeping an object's data private and letting other code change it only through methods that check the change. A bank account should not let anyone write acc.balance = -5000;.
public class Account {
private String holder;
private double balance;
public Account(String holder, double opening) {
this.holder = holder;
setBalance(opening);
}
public double getBalance() { // getter
return balance;
}
private void setBalance(double value) {
if (value < 0) throw new IllegalArgumentException("Balance cannot be negative");
balance = value;
}
public void deposit(double amount) {
if (amount <= 0) throw new IllegalArgumentException("Deposit must be positive");
balance += amount;
}
public String getHolder() {
return holder;
}
}
Now acc.balance = -5000; does not compile, and every change passes through a check.
Getters and setters
- A getter returns a field:
getBalance(). For abooleanfield it is oftenisActive(). - A setter changes a field after checking the value:
setAge(int age). - Leave out the setter for fields that must not change after creation (read-only).
Access modifiers
| Modifier | Same class | Same package | Subclass (other package) | Everywhere |
|---|---|---|---|---|
private | yes | no | no | no |
| (none, "package-private") | yes | yes | no | no |
protected | yes | yes | yes | no |
public | yes | yes | yes | yes |
Good default: fields private, the methods other classes need public.
static: belonging to the class
A normal (instance) field has one copy per object. A static field has one copy shared by the whole class.
public class Student {
private static int count = 0; // shared by all students
private final int id;
private String name;
public Student(String name) {
this.name = name;
count++;
id = count; // 1, 2, 3, ...
}
public static int getCount() {
return count;
}
}
new Student("Asha");
new Student("Ravi");
System.out.println(Student.getCount()); // 2
Static methods
- Called on the class:
Student.getCount(),Math.sqrt(9),Integer.parseInt("5"). - They have no
this, so they cannot use instance fields or instance methods directly. - That is why
main(which is static) cannot call a non-static method without an object.
Static blocks
A static { ... } block runs once, when the class is first loaded, to set up static data:
static final double[] GST_RATES;
static {
GST_RATES = new double[] {0, 5, 12, 18, 28};
}
Constants
public static final makes a class-wide constant: public static final int MAX_SEATS = 60;.
final in three places
finalvariable: its value cannot change after it is set.finalmethod: subclasses cannot override it.finalclass: no class can extend it (for exampleString).
Packages
A package groups related classes, like folders on a disk, and prevents name clashes.
package in.brainbit.school;
public class Student { ... }
- The
packageline must be the first statement in the file. - The folder structure must match:
in/brainbit/school/Student.java. - Convention: reverse domain name, all lowercase.
import
import java.util.Scanner; // one class
import java.util.*; // every class in java.util (not sub-packages)
import static java.lang.Math.PI; // a static member, used as PI
java.lang (String, Math, System, Integer) is imported automatically.
Built-in packages you will use
| Package | Has |
|---|---|
java.lang | String, Math, System, wrapper classes |
java.util | Scanner, ArrayList, HashMap, Arrays, Collections |
java.io | File and stream classes |
java.nio.file | Files, Path |
java.time | LocalDate, LocalDateTime |
java.sql | JDBC classes |
Example: an immutable Product class
public final class Product {
private final String code;
private final String name;
private final double price;
public Product(String code, String name, double price) {
if (price < 0) throw new IllegalArgumentException("price");
this.code = code;
this.name = name;
this.price = price;
}
public String getCode() { return code; }
public String getName() { return name; }
public double getPrice() { return price; }
}
All fields are private final and there are no setters, so a Product never changes after it is created. (A record, covered later, does this in one line.)
Common mistakes
- Making every field
public"to keep it simple" and losing all control over the data. - Writing setters that accept anything, which is no better than a public field.
- Using an instance field inside a
staticmethod: "non-static variable cannot be referenced from a static context". - Using a static field for data that belongs to each object (for example a static
name). - A package declaration that does not match the folder, so the class is not found.
Key points
- Encapsulation:
privatefields,publicmethods that check every change. private< package-private <protected<public.staticmembers belong to the class, are shared, and are used through the class name.- Static methods have no
thisand cannot touch instance members directly. - Packages group classes;
importbrings them into a file;java.langis always available.
Practice questions
1. Why should fields be private?
So other classes cannot put an object into an invalid state; every change has to go through a method that can check it.
2. Write a setAge method that rejects ages outside 0 to 120.
public void setAge(int age) {
if (age < 0 || age > 120) {
throw new IllegalArgumentException("Invalid age: " + age);
}
this.age = age;
}3. What does this print?
class Counter {
static int a = 0;
int b = 0;
Counter() { a++; b++; }
}
// in main:
Counter x = new Counter();
Counter y = new Counter();
System.out.println(Counter.a + " " + y.b);
2 1. a is shared and counts both objects; each object has its own b.
4. Which access level lets a class in the same package use a member, but not a class in another package?
Package-private: no modifier at all.
5. Where must Report.java be saved if it begins with package com.school.exam;?
In the folder com/school/exam/ under the source root.