Core Java

core25ClassesAndObjectsDemo

Path
pkg1core/core25ClassesAndObjectsDemo.java
Package
pkg1core
Study order
10
Run
Single-file source launch
Command
java pkg1core/core25ClassesAndObjectsDemo.java
Lesson
Back to the chapter

There is no in-browser runner. This is the file from the curriculum, unchanged.

pkg1core/core25ClassesAndObjectsDemo.java
1package pkg1core;2 3/*4 * core25ClassesAndObjectsDemo.java5 * -------------------------------6 * Classes as blueprints; objects as instances; fields vs behavior.7 *8 * EXPLANATION:9 *  - A class defines state (fields) and behavior (methods).10 *  - `new` allocates an object on the heap; the reference variable points to it.11 *  - Each object has its own copy of instance fields; static fields are shared.12 */13public class core25ClassesAndObjectsDemo {14 15    static class Book {16        String title;17        int pages;18 19        void describe() {20            System.out.println("  " + title + " (" + pages + " pages)");21        }22    }23 24    public static void main(String[] args) {25        Book a = new Book();26        a.title = "Effective Java";27        a.pages = 416;28 29        Book b = new Book();30        b.title = "Clean Code";31        b.pages = 464;32 33        System.out.println("Two distinct objects:");34        a.describe();35        b.describe();36 37        System.out.println("a == b ? " + (a == b));           // different references38        System.out.println("a.title == b.title ? " + (a.title == b.title)); // false (different Strings)39    }40}