Core Java

10 — Classes & Objects

Previous: 09 User Input · Next: 11 Constructors & Encapsulation

▶️ java pkg1core/core25ClassesAndObjectsDemo.java


Class = blueprint, Object = instance

java
1class Book {2    String title;3    int pages;4 5    void describe() {6        System.out.println(title + " (" + pages + " pages)");7    }8}9 10Book a = new Book();   // create object on heap11a.title = "Effective Java";12a.pages = 416;13a.describe();
Term Meaning
Class Defines fields (state) and methods (behavior)
Object A concrete instance created with new
Reference Variable pointing to an object (Book a)

Memory picture

code
1Book a ──────► [ Book object on heap ]2                  title = "Effective Java"3                  pages = 4164 5Book b ──────► [ different Book object ]6                  title = "Clean Code"7                  pages = 464

a == b is false — different objects, even if fields match.


Fields vs local variables

Field (instance) Local variable
Lives Inside object Inside method
Default 0, null, false Must assign before use
Scope Whole class (via this) Block only

`this` keyword

java
1class Person {2    String name;3    Person(String name) {4        this.name = name;   // disambiguate field vs parameter5    }6}

Practice

  1. Run core25ClassesAndObjectsDemo.
  2. Create a Student class with name, grade, and printReport() method.
  3. Create two students and call methods on each.

Next → 11 Constructors & Encapsulation Related → 01 Core Java