Classes & Objects
AP CSA: Classes & Objects
Goal: Understand the relationship between classes and objects, how reference variables work, and that all Java classes ultimately extend Object.
1) Class vs. Object
Class = blueprint or template. Object = one specific instance built from that blueprint.
Description
A class defines attributes (instance variables) and behaviors (methods). Creating an object with new allocates memory and returns a reference to that object.
// Example: simple class + object
class Dog {
String name;
int age;
void bark() {
System.out.println(name + " says woof!");
}
}
class Main1 {
public static void main(String[] args) {
Dog myDog = new Dog(); // object created
myDog.name = "Alo";
myDog.age = 3;
myDog.bark();
}
}
2) Reference Variables
Variables of reference type store the address (reference) of an object, not the object itself.
Description
Two variables can reference the same object. Assigning one reference to another does not make a copy of the object. They both will point to the same thing.
// Example: references point to the same object
class Main2 {
public static void main(String[] args) {
Dog d1 = new Dog();
d1.name = "Kai";
Dog d2 = d1; // both refer to the same Dog
d2.name = "Kairo"; // changes seen via d1 too
System.out.println(d1.name); // prints Kairo
}
}
Key Point: When Phone p2 = p1;, a second variable is created that points to the same phone object. Changes through one variable affect the other as well.
3) All Classes Are Subclasses of Object
Object is Java’s ultimate superclass. Every class directly or indirectly extends it.
Description
Because of this, every object has methods like toString(), equals(Object), and getClass() automatically (even if they weren’t programmed).
// Example: methods from Object
class Main3 {
public static void main(String[] args) {
Dog x = new Dog();
System.out.println(x.getClass().getName()); // prints class name
System.out.println(x.toString()); // default toString from Object
System.out.println(x instanceof Object); // true
}
}
Key Point: All Java objects inherit from Object, so they all have these built-in methods available.
🍿 Popcorn Hack (one cell)
Task: Complete the code below.
- Finish the
Bookclass by adding aprintInfo()method that prints title and pages. - In
Main, create oneBookobject, set its fields, and callprintInfo().
Keep it short—this is a quick check that you can define a class and create an instance.
// TODO: Finish and run in your Java environment
class Book {
String title;
int pages;
// TODO: write printInfo() to show: Title: <title>, Pages: <pages>
}
class MainPopcorn {
public static void main(String[] args) {
// TODO: make one Book, set its fields, and call printInfo()
}
}
Quick Self-Check (concepts)
- In one sentence, explain class vs. object.
- What does a reference variable store?
- Name one method every object has because it extends
Object.