Lesson 1.12
CSA Unit 1.12
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 myBook = new Book();
myBook.title = "The Java Journey";
myBook.pages = 250;
myBook.printInfo();
}
}
Title: The Java Journey, Pages: 250
Check In
-
Class vs. Object: A class is a blueprint that defines the structure and behavior of something, while an object is a specific instance created from that class.
-
Reference variable: It stores the memory address (reference) of the object, not the actual object itself.
-
Common method: Every object has the toString() method (inherited from the Object class).
Homework Hack 1
public class Student {
// Instance variables
String name;
int grade;
int pets;
int siblings;
// Main method
public static void main(String[] args) {
// Create 3 student objects
Student s1 = new Student();
s1.name = "Ava Johnson";
s1.grade = 10;
s1.pets = 2;
s1.siblings = 1;
Student s2 = new Student();
s2.name = "Liam Rivera";
s2.grade = 11;
s2.pets = 0;
s2.siblings = 3;
Student s3 = new Student();
s3.name = "Noah Patel";
s3.grade = 9;
s3.pets = 1;
s3.siblings = 2;
// Print each student's information
System.out.println(s1.name + " - Grade: " + s1.grade + ", Pets: " + s1.pets + ", Siblings: " + s1.siblings);
System.out.println(s2.name + " - Grade: " + s2.grade + ", Pets: " + s2.pets + ", Siblings: " + s2.siblings);
System.out.println(s3.name + " - Grade: " + s3.grade + ", Pets: " + s3.pets + ", Siblings: " + s3.siblings);
}
}
Ava Johnson - Grade: 10, Pets: 2, Siblings: 1
Liam Rivera - Grade: 11, Pets: 0, Siblings: 3
Noah Patel - Grade: 9, Pets: 1, Siblings: 2
Homework Hack 2
public class Student {
String name;
int grade;
int pets;
int siblings;
public static void main(String[] args) {
// Create 3 student objects
Student s1 = new Student();
s1.name = "Ava Johnson";
s1.grade = 10;
s1.pets = 2;
s1.siblings = 1;
Student s2 = new Student();
s2.name = "Liam Rivera";
s2.grade = 11;
s2.pets = 0;
s2.siblings = 3;
Student s3 = new Student();
s3.name = "Noah Patel";
s3.grade = 9;
s3.pets = 1;
s3.siblings = 2;
// Create a reference variable (nickname) for s1
Student nickname = s1;
// Output instance attributes for nickname
System.out.println("Nickname refers to: " + nickname.name);
System.out.println("Grade: " + nickname.grade);
System.out.println("Pets: " + nickname.pets);
System.out.println("Siblings: " + nickname.siblings);
}
}
Nickname refers to: Ava Johnson
Grade: 10
Pets: 2
Siblings: 1