A class is a blueprint that bundles state (fields) and behaviour (methods); an object is one instance of it living on the heap.
The four pillars of OOP
Declaring a class and creating objects
public class Main {
public static void main(String[] args) {
BankAccount a = new BankAccount("Asha", 500);
BankAccount b = new BankAccount("Ravi", 100);
a.deposit(250);
b.withdraw(30);
System.out.println(a.describe());
System.out.println(b.describe());
System.out.println("accounts opened: " + BankAccount.count);
}
}
class BankAccount {
String owner; // instance field: one copy per object
double balance;
static int count = 0; // static field: one copy per class
BankAccount(String owner, double balance) { // constructor
this.owner = owner;
this.balance = balance;
count++;
}
void deposit(double amount) { balance += amount; }
void withdraw(double amount) { balance -= amount; }
String describe() { return owner + " has " + balance; }
}Asha has 750.0
Ravi has 70.0
accounts opened: 2What new does
Load the class
If
BankAccountisn't loaded yet, the class loader loads, links and initialises it (static fields/blocks run once).Allocate
Memory for the object is reserved on the heap; every field gets its default value (
0,false,null).Initialise
Field initialisers and instance initializer blocks run, then the constructor body.
Return a reference
newevaluates to a reference (think: a safe pointer) that is stored in the variable.
References, not objects, live in variables
public class Main {
public static void main(String[] args) {
Point p1 = new Point();
p1.x = 1;
Point p2 = p1; // copies the reference, not the object
p2.x = 99;
System.out.println(p1.x); // same object
System.out.println(p1 == p2); // same reference?
Point p3 = new Point();
p3.x = 99;
System.out.println(p1 == p3); // different objects
Point nothing = null;
System.out.println(nothing == null);
}
}
class Point { int x, y; }99
true
false
trueDefault values of fields
| Field type | Default |
|---|---|
byte, short, int, long | 0 |
float, double | 0.0 |
char | '\u0000' |
boolean | false |
Any reference (String, arrays, objects) | null |
Instance vs class members
| Instance member | Static (class) member | |
|---|---|---|
| Belongs to | each object | the class itself |
| Copies | one per object | exactly one |
| Accessed via | obj.field | ClassName.field |
Can use this? | Yes | No |
What is the difference between a class and an object?
Is p2 = p1 a copy of the object?
Where do objects and references live?