Java•Classes & OOP
Java Classes and Object-Oriented Programming (OOP)
Learn encapsulation, constructor initialization, instance methods, and the this keyword in Java.
Syntax
public class ClassName {
private int field;
public ClassName(int f) { this.field = f; }
}
Parameters & Values
Key components and acceptable values for this structure:
| Parameter | Type | Description |
|---|---|---|
| private | Access Modifier | Restricts visibility to enclosing class. |
| this | Keyword | Refers to current object instance. |
Ready-to-Run Code Example
Executable in CompilraRun this complete, working example directly without installing Java locally:
class BankAccount {
private String holder;
private double balance;
public BankAccount(String holder, double initialBalance) {
this.holder = holder;
this.balance = initialBalance;
}
public void deposit(double amount) {
if (amount > 0) {
this.balance += amount;
System.out.printf("Deposited $%.2f. New Balance: $%.2f%n", amount, this.balance);
}
}
public double getBalance() {
return this.balance;
}
}
public class Main {
public static void main(String[] args) {
BankAccount account = new BankAccount("Alice", 500.0);
account.deposit(250.0);
System.out.println("Final Account Balance: $" + account.getBalance());
}
}Expected Output:
Deposited $250.00. New Balance: $750.00 Final Account Balance: $750.0
How It Works: Step-by-Step
- Lines 2-3: Encapsulates state in private fields.
- Lines 5-8: Constructor initializes instance variables using this.holder.
- Lines 10-15: deposit method validates input and mutates balance safely.
Key Concepts
- Encapsulation prevents direct external manipulation of private class fields.
- Constructors share the class name and have no return type.
- Use getters and setters to enforce business validation logic.
Common Mistake: Shadowing class fields without using the this keyword in constructor
Writing holder = holder assigns the parameter to itself, leaving the class field null.
❌ Incorrect
public User(String name) { name = name; // Bug! Does NOT set this.name }✅ Correct
public User(String name) { this.name = name; }Related Java Tutorials & Compiler
Java Inheritance, Polymorphism, and the super Keyword
Extend classes with extends, invoke parent logic with super, and override methods with @Override.
Java Methods: Static Methods, Return Values, and Overloading
Learn how to declare methods, pass arguments, return values, and overload method signatures.
Java Exception Handling: try, catch, finally, and throws
Catch and throw checked and unchecked exceptions safely using try-catch-finally blocks.
Java Online Compiler
Open in Compilra IDE
Run and test Java on Compilra
Execute this code snippet with pre-supplied standard input (stdin) in Compilra’s cloud compiler.