Core Java
10 — Classes & Objects
Previous: 09 User Input · Next: 11 Constructors & Encapsulation
▶️ java pkg1core/core25ClassesAndObjectsDemo.java
Class = blueprint, Object = instance
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
1Book a ──────► [ Book object on heap ]2 title = "Effective Java"3 pages = 4164 5Book b ──────► [ different Book object ]6 title = "Clean Code"7 pages = 464a == 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
1class Person {2 String name;3 Person(String name) {4 this.name = name; // disambiguate field vs parameter5 }6}Practice
- Run
core25ClassesAndObjectsDemo. - Create a
Studentclass withname,grade, andprintReport()method. - Create two students and call methods on each.
Next → 11 Constructors & Encapsulation Related → 01 Core Java
Source named in this chapter
- core25ClassesAndObjectsDemopkg1core/core25ClassesAndObjectsDemo.java