Lesson 16 / 38
Classes & Objects
Define a class with fields and methods, create objects with new on the heap, and understand this plus the difference between instance and static members.
Class = blueprint
A class defines state (fields) and behaviour (methods). An object is one instance created with new, living on the heap and referenced by a variable.
A small class
this refers to the current instance. Instance methods act on one object's fields; static members belong to the class itself.
public class Counter {
private int value;
public void increment() { this.value++; }
public int get() { return value; }
}
Counter c = new Counter();
c.increment();
System.out.println(c.get()); // 1