Java:Java Classes and Object-Oriented Programming (OOP)
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:

ParameterTypeDescription
privateAccess ModifierRestricts visibility to enclosing class.
thisKeywordRefers to current object instance.

Ready-to-Run Code Example

Executable in Compilra

Run 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

Run and test Java on Compilra

Execute this code snippet with pre-supplied standard input (stdin) in Compilra’s cloud compiler.

Java Online Compiler