A class is a type: it names a set of values (instances) and the operations allowed on them. An object is a particular instance allocated on the heap (unless it is a value-class experiment — not LTS production practice). The factory metaphor is useful, then you outgrow it: a class is also a namespace, a lock target (Foo.class), a class-loader key, and a compile-time type.
Car c holds a reference, not the car. c = null means “no instance,” not “an empty car.”Mental model: assignment and argument passing copy the reference. Two variables can name one object. Equality of objects is not the same as equality of references — see the Equals & hashCode topic.
Definition: a class declares fields, methods, constructors, nested types, and (optionally) an initializer. It is a user-defined reference type.
new runs a constructor and returns a reference to a new instance (except when you intern/cache yourself).int is; the JVM lays out fields.final class: no subclasses. Prefer this until you have a real polymorphism need.abstract class: cannot be instantiated; may have state and constructors for subclasses.public final class Money {
private final long cents;
private final String currency;
public Money(long cents, String currency) {
this.cents = cents;
this.currency = java.util.Objects.requireNonNull(currency);
}
}
Definition: an object is an instance of a class (or array). It has identity (you can tell it from another instance even if fields match), state (instance fields), and a runtime class (getClass()).
Student.class) exists once per class loader. Instances are many.new it.new is not the only way to get an instance: deserialization, cloning (avoid), reflection, and enum constants all produce instances under specific rules.Memory (revision level): the reference lives in a local slot, a field, or an array element. The object header + fields live on the heap. GC reclaims unreachable objects. There is no deterministic destructor; finalize is deprecated for removal. Use AutoCloseable and try-with-resources for cleanup.
| Idea | Java | Notes |
|---|---|---|
| State | Instance fields | Default 0 / false / null if not set. Prefer explicit construction. |
| Shared state | Static fields | One per class loader, not per instance. Easy to misuse. |
| Behaviour | Instance methods | Dispatch uses the runtime class (virtual invoke). |
| Identity | ==, System.identityHashCode | Not equals unless you did not override it. |
| Type | Declared type vs runtime class | A List variable may point at an ArrayList. |
Local variables are not part of the object. They live on the stack (or in registers) for the duration of the method.
Student s1 = new Student();
s1.enrol("CS101");
new allocates, runs instance initializers and the chosen constructor, then yields a reference.new (Student s;) is an uninitialized local — using it does not compile. A field of type Student defaults to null.Student s;
s.enrol("CS101"); // compile error: s might not have been initialized
Student t = null;
t.enrol("CS101"); // compiles; throws NullPointerException
A constructor’s name matches the class. It has no return type (not even void). If you write none, the compiler supplies a public no-arg constructor that calls super(). If you write any constructor, the default disappears.
this(…) delegates to another constructor in the same class; it must be the first statement.super(…) calls a superclass constructor; also must be first (or, in recent Java, in the explicit-constructor-invocation position). Every constructor eventually chains to Object.this in an instance method or constructor is the object under construction / the receiver.public final class Interval {
private final int start;
private final int end;
public Interval(int start, int end) {
if (end < start) throw new IllegalArgumentException("end < start");
this.start = start;
this.end = end;
}
public Interval(int end) {
this(0, end);
}
}
Pitfall: calling an overridable instance method from a constructor. The subclass fields are not yet initialized; you can observe 0/null or publish this too early (this-escape). Keep constructors dull: assign, validate, done. Java 21+ has warnings for this-escape.
Static initializers run when the class is initialized (first active use). Failures become ExceptionInInitializerError. Do not do I/O you cannot afford at class-load time.
Identity (==) | Equality (equals) | |
|---|---|---|
| Asks | Same object? | Same value, as defined by the class? |
| Default equals | Same as == | Object.equals is identity |
| Value types (String, records you write well) | Usually the wrong question | The right question |
| Mutable entities (a Session, a Socket) | Often what you mean | Overriding equals can be harmful |
Two new Student(1) objects are never ==. They may be equals if you define equality on the id. If a Student is an entity that changes name, identity is usually the database id, and you must still obey the hashCode contract if you put it in a HashSet — prefer immutable keys. Full rules live in the Equals & hashCode topic.
Definition: encapsulation bundles state with the methods that maintain its invariants, and hides representation. Access modifiers are the language tool; discipline is the rest.
| Modifier | Class | Package | Subclass | World |
|---|---|---|---|---|
private | yes | no | no | no |
| package-private | yes | yes | no* | no |
protected | yes | yes | yes | no |
public | yes | yes | yes | yes |
*A subclass in another package does not see package-private members. protected members are visible to subclasses, with extra rules for instances that are not this.
private unless you have a measured reason (constants: public static final immutable values).List is not encapsulation. Return a copy or an unmodifiable view.// Incorrect
public List<String> tags;
public List<String> getTags() { return tags; }
// Correct
private final List<String> tags = new ArrayList<>();
public List<String> getTags() { return List.copyOf(tags); }
final classes.// Inheritance used as reuse — brittle
class Stack extends ArrayList<Object> { }
// Composition — you control the surface
class Stack {
private final ArrayList<Object> items = new ArrayList<>();
public void push(Object o) { items.add(o); }
}
When not to create an object: if a static function on a utility class is enough (stateless math); if you should cache/intern; if a record or enum constant already exists; if you were about to new Boolean(false) (deprecated — use Boolean.FALSE / autoboxing).
this.== for identity, equals for value. Do not override equals on a mutable entity you put in a HashSet.final classes. Inherit only for real subtype polymorphism.~ Good luck with your revision! ~