Java Introduction to Classes
Table of Contents + β
In the last lesson you learned about Java varargs. Now for the biggest step in the course. Real things are data and behavior at once, and Java models them with a class.
- A car has data like color and speed.
- A car has behavior like drive and brake.
- Both belong to one single thing. That is what a class captures.
π€ Why do classes exist?
To store a student with only the tools you have so far, you would use separate variables.
// β The data is scattered across loose variablesString studentName = "Alex";int studentAge = 20;String studentCourse = "Java";These three variables describe one student, but nothing says they belong together. With one student it looks fine. The trouble starts as the program grows:
- A second student needs three more variables, and you must track which name goes with which age.
- Passing a student into a method means passing name, age, and course as three separate arguments.
- Adding a grade later means a new loose variable for every student.
What we want is one thing called a Student that holds name, age, and course as a unit. A class bundles related data and behavior into one package so they travel together.
ποΈ What is a class?
A class is a blueprint. Think of the architectural plan for a house:
- The plan describes a house: where rooms go, how many windows, where the door is.
- You cannot live in the plan. It is a description, not the real thing.
- From one plan you build many real houses, each with its own address and paint color.
So a Student class is the plan. It says βa student has a name, an age, and a courseβ. By itself it is not any actual student. It is the shape every future student will follow.
π§© Class vs object
Never mix up these two:
- A class is the blueprint. It describes what a thing is. The plan, not the real thing.
- An object is the real thing built from that blueprint. It lives in memory and holds real values. One class, many objects.
The clearest picture is a cookie cutter. The cutter is one shape, not a cookie. Press it into dough again and again and you get many real cookies. Each cookie is a separate object. So a Student class is the cutter, and each student you create is a cookie made from it.
Blueprint vs real thing
The class is written once. It is the plan. An object is a real thing made from the plan. If this feels fuzzy, go back to the house plan. One plan, many houses. Each house is real and stands on its own. That is exactly how one class gives you many objects.
π Writing a first class
The data items inside a class are called fields (also called instance variables, the same thing). Here is a Student class with a name, an age, and a course.
class Student { String name; // a field int age; // a field String course; // a field}That is a complete, working class.
- The word
classstarts the blueprint, andStudentis its name. - Inside the curly braces we list the fields: a
String name, anint age, and aString course. - The fields describe what every Student object will hold. They hold no values yet.
This is still only a plan. To get an actual student you build an object from the class. We keep that light here since the next lessons go deeper.
public class Main {
public static void main(String[] args) { Student s1 = new Student(); // β
build a real Student object s1.name = "Alex"; s1.age = 20; s1.course = "Java";
System.out.println(s1.name + " is " + s1.age + " and studies " + s1.course); }}
class Student { String name; int age; String course;}- The word
newbuilds one real Student object from the blueprint. - The variable
s1refers to that object. - The dot, like
s1.name, reaches into the object to set or read a field. Sos1.name = "Alex"sets that studentβs name.
Output
Alex is 20 and studies JavaThe full story of building objects waits for the next lesson. The key split: class Student { ... } is the blueprint, and new Student() builds a real thing from it.
π A class holds data and behavior
Fields are only half the story. A class can also hold methods, which are behaviors the object can do. Like the car: data (color, speed) and behavior (drive, brake) live together in one place. Here is a Dog class that holds a name and an age, and can bark and describe itself.
public class Main {
public static void main(String[] args) { Dog d1 = new Dog(); d1.name = "Bruno"; d1.age = 3;
d1.bark(); // β
call a behavior on the object d1.describe(); }}
class Dog { String name; // field: data the dog remembers int age; // field: data the dog remembers
void bark() { // method: behavior System.out.println(name + " says: Woof!"); }
void describe() { // method: behavior System.out.println(name + " is " + age + " years old."); }}Look at how the class is built:
Doghas two fields,nameandage. That is the data it holds.- It has two methods,
barkanddescribe. That is the behavior it can do. - Inside
bark, the wordnamemeans βthe name of this dogβ, so the method works on whichever object is before the dot. d1.bark()runs the bark behavior on this dog. The dot works for methods just like for fields.
Output
Bruno says: Woof!Bruno is 3 years old.That is the full shape of a class: data and behavior bundled into one blueprint. Everything about a dog lives inside the Dog class.
π€ Naming classes: PascalCase
Class names always use PascalCase:
- It starts with a capital letter.
- Every new word inside the name also starts with a capital letter.
- No spaces and no underscores.
// β
correct class names: PascalCaseclass Student {}class BankAccount {}class HttpRequest {}
// β wrong style: do not write class names like thisclass student {} // should start with a capital Sclass bank_account {} // no underscores, capitalize each wordWhy the capital first letter?
- A class stands for a kind of thing, like a noun:
Student,Car,BankAccount. - It makes classes easy to spot. A capitalized word means a class; a lowercase word means a variable or method.
π One public class per file
When a class is marked public, the file name must match the class name exactly. The file that holds public class Student must be called Student.java, same spelling, same capital letters.
// β
This must be saved in a file named Student.javapublic class Student { String name; int age;}Save public class Student in any other file name and the compiler refuses to build it. You get this error.
File name mismatch
error: class Student is public, should be declared in a file named Student.javaThe safe habit:
- Put one public class in each file, named after that class.
public class BankAccountgoes inBankAccount.java. - You can place small helper classes without
publicin the same file. That is why earlier examples hadMainandStudenttogether. - The clean way in real projects is one public class per file, so finding code is easy: want
Student, openStudent.java.
β οΈ Common Mistakes
A few class slip-ups to watch for early.
- Confusing the class with the object. The class is the blueprint. The object is the real thing made with
new. You do not use the class itself as data.
// β trying to use the class itself as if it were a studentStudent.name = "Alex";
// β
build an object first, then use itStudent s1 = new Student();s1.name = "Alex";- Starting a class name with a lowercase letter. Class names use PascalCase. A lowercase start works but breaks the convention every Java reader expects.
// β wrong styleclass car {}
// β
correctclass Car {}-
A public class name that does not match the file name. A
public class Studentmust live inStudent.java. Any other file name will not compile. -
Thinking the class holds values. The class only describes the shape. The fields hold no values until you build an object and set them. The blueprint is empty by design.
β Best Practices
Good habits when you write classes.
- Name a class with a capital noun.
Student,Car,BankAccount. A class stands for a kind of thing, so name it like a thing.
// β
clear, thing-like class namesclass Invoice {}class UserProfile {}-
Group related data and behavior into one class. If pieces of data always travel together, they belong in the same class. The methods that work on that data belong there too.
-
Keep one public class per file, named after the class. Put
public class OrderinOrder.java. It keeps your project easy to navigate. -
Use clear field names.
name,age,balance. The field name should tell you what it holds without any comment.
// β
the names explain themselvesclass BankAccount { String owner; double balance;}π§© What Youβve Learned
You have taken your first step into OOP. Letβs recap.
- β A class is a blueprint that describes what data a kind of thing holds and what it can do.
- β A class is the plan; an object is the real thing built from it. Cookie cutter versus cookie.
- β Classes exist to model real-world things and to bundle related data and behavior into one unit.
- β The data inside a class is stored in fields, and the behavior is stored in methods.
- β
Class names use PascalCase, starting with a capital letter, like
StudentandBankAccount. - β
A
publicclass must be saved in a file with the same name, likeStudent.java.
Check Your Knowledge
Test what you learned. Pick an answer for each question, then click Check.
- 1
What is a class in Java?
Why: A class is a blueprint or plan. The real things built from it are objects.
- 2
Which line correctly describes the class vs object difference?
Why: The class is the cookie cutter (the plan), and each object is a real cookie made from it.
- 3
Which is the correct PascalCase class name?
Why: Class names use PascalCase: a capital first letter and a capital for each new word, like BankAccount.
- 4
Where must a public class named Student be saved?
Why: A public class must live in a file with the exact same name, so public class Student goes in Student.java.
π Whatβs Next?
Now you know what a class is and how it differs from an object. Next youβll build classes of your own from scratch and turn them into real objects, going deeper into fields, methods, and creating objects with new. Letβs keep going.