Unit 1.12 - Using Objects
Categories: homeworkJava homework assignment covering classes, objects, reference variables, and object-oriented programming concepts
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 = "Harry Potter";
myBook.pages = 309;
myBook.printInfo();
}
}
Output:
Title: Harry Potter, Pages: 309
Quick Self-Check Answers
1) In one sentence, explain class vs. object. A class is a blueprint or template that defines the structure and behavior of objects, while an object is an instance of a class 2) What does a reference variable store? A reference variable stores the memory address of an object but it doesn’t store the actual object 3) Name one method every object has because it extends Object. Every object has the toString() method or equals() or getClass() inherited from the Object class.
Homework
public class Student {
String name;
int grade;
int pets;
int siblings;
public Student(String name, int grade, int pets, int siblings) {
this.name = name;
this.grade = grade;
this.pets = pets;
this.siblings = siblings;
}
public void printInfo() {
System.out.println("Name: " + name);
System.out.println("Grade: " + grade);
System.out.println("Pets: " + pets);
System.out.println("Siblings: " + siblings);
System.out.println();
}
public static void main(String[] args) {
Student s1 = new Student("Ethan", 10, 2, 1);
Student s2 = new Student("Sophia", 11, 1, 3);
Student s3 = new Student("Liam", 12, 0, 2);
s1.printInfo();
s2.printInfo();
s3.printInfo();
Student nickname = s2;
System.out.println("Nickname reference details:");
nickname.printInfo();
nickname.name = "Sophie";
System.out.println("After changing nickname:");
s2.printInfo();
}
}