Plus
$7.99 / month
- Nemotron Nano 12B VL
- Nemotron Nano 30B
- 20 AI credits/week
Save your current position in the course
Certificates are issued to Unlimited subscribers who finish a course. Your progress is saved either way — upgrade whenever you want yours.
Report a problem with this course via Discord
View available keyboard shortcuts
Reset all section and file completion progress
In the world of software engineering, we are often tasked with representing complex real-world systems—like a banking network, a social media platform, or a physics engine—within the rigid confines of computer code. To bridge this gap, Java utilizes Object-Oriented Programming (OOP). While previous units focused on using pre-existing classes (like String or Scanner), Unit 3: Class Creation is where you transition from being a consumer of code to an architect of code.
Imagine you are designing a video game. Instead of managing thousands of individual variables for every player’s health, position, and inventory, you can create a single blueprint: the Player class. This blueprint defines what every player has (attributes) and what every player does (behaviors). This process of "bundling" data and behavior is the cornerstone of professional software development.
In this chapter, we will explore the philosophical underpinnings of Abstraction, the protective walls of Encapsulation, and the technical mechanics of Constructors, Methods, and Scope. By the end of this unit, you will be able to design robust, reliable, and reusable software components that adhere to the rigorous standards of the AP Computer Science A curriculum.
Car is the class, "My 2022 Blue Sedan" is the object.public, private) that set the visibility and accessibility of classes, variables, and methods.this Keyword: A reference to the current object whose method or constructor is being called.Abstraction allows programmers to manage complexity.
Point class. We interact with the Point object rather than the raw integers.Math.sqrt(16.0), you do not care if the computer uses the Babylonian method or Newton's method. You only care that it returns $4.0$.Design Process: Before writing a single line of code, developers use "Natural Language" or UML (Unified Modeling Language) to plan.
BankCard has a balance).BankCard can withdraw).Software does not exist in a vacuum.
A standard class in this course follows a specific structure:
| Component | Visibility | Purpose |
|---|---|---|
| Class Header | public |
Defines the name of the blueprint. |
| Instance Variables | private |
Stores the state/data (Encapsulation). |
| Constructors | public |
Initializes the private variables. |
| Methods | public / private |
Defines the logic and behaviors. |
Encapsulation is achieved by making variables private. This prevents external classes from "corrupting" the data. For example, if age is private, we can prevent a user from setting age = -500 by using a method that checks for validity.
Constructors are called using the new keyword.
int $\rightarrow 0$double $\rightarrow 0.0$boolean $\rightarrow false$The "Mutable Object" Trap: If a constructor takes an object (like a Date) as a parameter, storing that exact reference allows the caller to change the object outside the class. To maintain encapsulation, we should store a copy of the object.
Methods represent behaviors.
return is executed, the method terminates immediately. Any code below it in that logic path is unreachable.Pass-by-Value (Primitives):
If we have a method increment(int n) and we call increment(x), a copy of the value of $x$ is made. The original $x$ remains unchanged.
When an object is passed, the reference (the address in memory) is copied.
The keyword static means "belongs to the class."
final) or counters.Math.abs()). this because they don't belong to a specific instance.private int x;
public void setX(int x) {
// The parameter 'x' shadows the instance variable 'x'.
// To reach the instance variable, we need 'this.x'.
}
this is a reference to the current object.
this cannot be used in static contexts.When we use System.out.println(5 + 10);, we do not know how Java converts the integer $15$ into pixel patterns on a screen. We only care that the behavior is consistent. This is procedural abstraction.
Instead of tracking $x_1, y_1, x_2, y_2$ separately, we design:
$$Area = |x_2 - x_1| \times |y_2 - y_1|$$
By creating a Rectangle class, we abstract these four coordinates into one "shape" concept.
String name, int id, double gpa.updateGPA(), getName().public class BankAccount {
private double balance; // Private protects the money
public void deposit(double amount) {
if (amount > 0) {
balance += amount;
}
}
}
If balance were public, someone could write account.balance = -1000000;.
If a class Gadget has private int serial; private boolean isActive;, and we call new Gadget(), the state is:
$$serial = 0, isActive = false$$
Gadget g = new Gadget();
new allocates memory.0x7A1) is stored in g.A Circle class might have:
public Circle() (sets radius to 1.0)public Circle(double r) (sets radius to r)public void addFive(int n) { n = n + 5; }
// Calling:
int x = 10;
addFive(x);
// Result: x is still 10.
$x_{original} = 10 \rightarrow n_{copy} = 10 \rightarrow n_{copy} = 15$. The original is untouched.
public void reset(Point p) { p.setX(0); }
// Calling:
Point myPt = new Point(5, 5);
reset(myPt);
// Result: myPt now has X = 0.
Both myPt and p hold the same memory address.
public Point getLocation() {
return this.location;
}
If location is a mutable object, the caller can now change the object's internal state. This is a common security/reliability risk.
public class Robot {
private static int totalRobots = 0;
public Robot() {
totalRobots++;
}
}
Every time new Robot() is called, the same variable totalRobots increments.
public static final double PI = 3.14159;
static: Only one copy exists.final: The value cannot be changed after initialization.public static double calculateInterest(double principal, double rate) {
return principal * rate;
}
Called as Bank.calculateInterest(100, 0.05). No object needed.
public class Hero {
private int health;
public Hero(int health) {
this.health = health; // this.health is the instance var, health is the param
}
}
public void doWork() {
int x = 5;
if (true) {
int x = 10; // ERROR: x is already defined in this method scope.
}
}
A student uses the "Apache Commons" library for complex math. Since it is open source, they can include it if they follow the license. Using a paid library without paying is a violation of legal standards.
public void setScore(int s) {
if (s >= 0 && s <= 100) {
score = s;
}
}
Ensures $0 \le score \le 100$.
public String getName() {
return name;
}
Provides "read-only" access to a private variable.
public int checkSign(int n) {
if (n > 0) return 1;
if (n < 0) return -1;
return 0;
System.out.println("Done"); // UNREACHABLE CODE ERROR
}
Student s;
The variable s exists in the stack but points to null. Attempting s.getName() results in a NullPointerException.
public Team(Coach c) {
// Instead of this.myCoach = c;
this.myCoach = new Coach(c.getName()); // Create a new object to avoid aliasing
}
A method to calculate the hypotenuse:
$$c = \sqrt{a^2 + b^2}$$
public double getHypotenuse(double a, double b) {
return Math.sqrt(a*a + b*b);
}
Methods can take multiple types:public void updateLog(String msg, int severity, double timestamp)
The order of arguments must match the signature exactly.
Instead of one giant processOrder() method, we break it down:
validatePayment()checkInventory()generateReceipt()If a CreditScore class design uses zipCode as an attribute, it might unintentionally reinforce socioeconomic biases. Programmers must consider these impacts during the design phase.
Car car1 = new Car("Red");
Car car2 = car1;
car2.setColor("Blue");
// car1 is now Blue because they point to the same memory.
private final int ID_NUMBER;
Must be initialized in the constructor and can never be changed again for that object.
public void process() {
DataAnalyzer.analyze(this); // Passes the entire current object to another class
}
A flight control system class must have $100%$ reliability. Developers use unit tests to verify that Altitude objects never have a negative value attribute.
public class Logic {
private int val = 20;
public void printVal() {
int val = 50;
System.out.println(val); // Prints 50
System.out.println(this.val); // Prints 20
}
}
If you define public MyClass(int x) {}, Java removes the automatic no-argument constructor. Calling new MyClass() will now cause a compile error.
public void birthday(Person p) {
p.setAge(p.getAge() + 1);
}
Even though the reference is passed by value, the object's internal state is permanently modified.
Void methods are used for their "side effects" (changing instance variables or printing), not for returning data.
Instance variables are declared outside of all methods. Their scope is the entire class.
public double getCircleArea(double r) {
return Math.PI * Math.pow(r, 2);
}
The expression is evaluated first, then the single resulting value is returned.
Right-click any tab and choose Split screen to view it here.
Course Mastery Certificates require an active Unlimited subscription at the time of generation and 100% course completion. They recognise learning content completion only — not an accredited qualification, licence, or professional credential unless explicitly stated. edusolum may modify eligibility, design, and issuance requirements per its Terms of Service.