Classes and objects

Fields, constructors, encapsulation and static members.

A class is a blueprint and an object is one instance of it. Keep fields private and expose methods, so that the class can protect its own rules. This is called encapsulation.

Java
class Account {
  private final String owner;
  private int balance;

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

  void deposit(int amount) {
    if (amount <= 0) {
      throw new IllegalArgumentException("Amount must be positive");
    }
    balance += amount;
  }

  int getBalance() {
    return balance;
  }

  String getOwner() {
    return owner;
  }
}

public class Main {
  public static void main(String[] args) {
    Account a = new Account("Meena");
    a.deposit(500);
    System.out.println(a.getOwner() + " " + a.getBalance());
  }
}
Output
Meena 500

static means a member belongs to the class, not to one object. this refers to the current object.

โ† MethodsInheritance and interfaces โ†’