Phase 9 of 20 · Topic 9.1

Classes, Objects & Heap Memory References

1Concept

A Class is a compile-time blueprint defining state (fields) and behavior (methods). An Object is a runtime instance allocated on the Heap via the `new` operator. Variables store references (memory pointers) on the thread Stack pointing to the object on the Heap.

2Architecture Diagram

[ Thread Stack Frame ]                [ JVM Heap Memory ]
  serverRef (Pointer: 0x7FFF01) ---> [ ServerInstance Object ]
                                      - hostname: "prod-api-01"
                                      - maxMemory: 32768

3Code Example

Core Java
public class ObjectLifecycleDemo {
    static class CloudServer {
        String hostname;
        int ramGb;

        public CloudServer(String hostname, int ramGb) {
            this.hostname = hostname;
            this.ramGb = ramGb;
        }
    }

    public static void main(String[] args) {
        CloudServer server1 = new CloudServer("aws-us-east-1", 64);
        CloudServer server2 = server1; // Reference copy: both point to identical heap object

        server2.hostname = "aws-us-west-2";
        System.out.println("server1 hostname: " + server1.hostname);
        System.out.println("server2 hostname: " + server2.hostname);
    }
}

4Expected Output

server1 hostname: aws-us-west-2
server2 hostname: aws-us-west-2

5Key Takeaways

  • Object variables contain references, not the actual object data itself.
  • Unreferenced heap objects are eventually reclaimed by the Garbage Collector.
  • Default constructor is generated by javac ONLY if no explicit constructors are declared.