Popcorn Hack 1

class Book {
    String title;
    int pages;

    void printInfo() {
        System.out.println("Title: " + title + ", Pages: " + pages);
    }
}

class MainPopcorn {
    public static void main(String[] args) {
        Book b = new Book();
        b.title = "The Hobbit";
        b.pages = 310;
        b.printInfo();
    }
}

MainPopcorn.main(null);


Title: The Hobbit, Pages: 310

Quick Self-Check

  1. A class is a blueprint or template for creating objects, and these are specific instances of that class.
  2. A reference variable stores the memory address or reference of an object, not the object itself.
  3. Every object inherits the toString() method from the Object class.

Homework

class Student {
    String name;
    int grade;
    int pets;
    int siblings;

    void printInfo() {
        System.out.println("Name: " + name + ", Grade: " + grade + ", Pets: " + pets + ", Siblings: " + siblings);
    }
}

class MainStudents {
    public static void main(String[] args) {
        // Creating three students
        Student s1 = new Student();
        s1.name = "Ahaan";
        s1.grade = 10;
        s1.pets = 1;
        s1.siblings = 0;

        Student s2 = new Student();
        s2.name = "Arnav";
        s2.grade = 11;
        s2.pets = 2;
        s2.siblings = 1;

        Student s3 = new Student();
        s3.name = "Nikhil";
        s3.grade = 12;
        s3.pets = 0;
        s3.siblings = 2;

        // Print all students
        s1.printInfo();
        s2.printInfo();
        s3.printInfo();

        System.out.println("------");

        // Create a nickname which references Arnav
        Student nick = s2;
        nick.name = "Arn"; // nickname for Arnav

        // Output instance attributes 
        nick.printInfo();
        System.out.println("Original reference also updated:");
        s2.printInfo(); 
    }
}

MainStudents.main(null);

Name: Ahaan, Grade: 10, Pets: 1, Siblings: 0
Name: Arnav, Grade: 11, Pets: 2, Siblings: 1
Name: Nikhil, Grade: 12, Pets: 0, Siblings: 2
------
Name: Arn, Grade: 11, Pets: 2, Siblings: 1
Original reference also updated:
Name: Arn, Grade: 11, Pets: 2, Siblings: 1