Start With the Problem#
The StudyBuddy report in Java Basics Ch 9 kept its data like this:
String[] students = { "Priya", "Rahul", "Aisha", "Vikram" };
int[] correctAnswers = { 18, 13, 20, 9 };
boolean[] onTime = { true, true, false, true };Three separate arrays, linked only by "position 2 in each array is Aisha". Now imagine the real app: each student also has an email, a list of notes, a quiz history and a credit balance. That's ten parallel arrays. Sort one of them by score and forget the others — every student now has someone else's email. Add a student and miss one array — everything after is shifted.
What we want is one thing called a Student that holds a name, an answer count and an on-time flag together, and that knows how to compute its own score. Java lets you invent such types. That's what this file teaches — and how those things actually live in memory.
The Plain Picture#
An architect draws one blueprint for a house: "3 rooms, 1 kitchen, a door here". From that blueprint a builder can build many houses. Each house is real and separate — paint one blue, and the others stay white — but they all follow the same plan.
The Real Names#
A class is the blueprint: it defines a new type by saying what data each thing of that type has and what it can do.
An object (or instance) is one house built from the blueprint.
The data each object holds are its fields (also called instance variables or attributes).
The things it can do are its methods (from Java Basics Ch 7, now attached to objects — Ch 3).
newbuilds an object:new Student(...).
Under the Hood#
class Student {
String name; // fields: every Student object gets its own copy of these
int score;
}Student priya = new Student(); // build one object
priya.name = "Priya"; // the dot (.) reaches inside an object
priya.score = 180;
Student rahul = new Student(); // a second, completely separate object
rahul.name = "Rahul"; Class Student (the blueprint) Objects (the houses)
┌──────────────────────┐ ┌──────────────────┐ ┌──────────────────┐
│ String name │ ── new ──▶ │ name = "Priya" │ │ name = "Rahul" │
│ int score │ │ score = 180 │ │ score = 0 │
└──────────────────────┘ └──────────────────┘ └──────────────────┘Fields get default values — 0, false, null — just like array elements (Java Basics Ch 8), so rahul.score starts at 0.
(Local variables in methods don't; Java Basics Ch 2.)
One class per concept. In StudyBuddy you'd have Student, Note, Quiz, Question. Choosing these well is the heart of
object-oriented design (Object-Oriented Programming, and Low-level design (coming soon)).
Check yourself
3 questionsClass vs object?
Show answerHide answer
A class is the blueprint/type definition; an object is one instance built from it.
What are fields?
Show answerHide answer
The data each object holds, declared in the class.
If you change priya.score, does rahul.score change? Why?
Show answerHide answer
No — each object has its own copy of every (non-static) field.