Classes are one of the most fundamental concepts in Java programming. Think of a class as a blueprint or template that describes what something should look like and what it can do.
Imagine you’re designing a house. Before you build the actual house, you create blueprints that show:
-
What rooms the house will have
-
How big each room will be
-
Where the doors and windows go
-
What the house can do (provide shelter, have electricity, etc.)
A Java class works the same way. It’s a blueprint that describes:
-
What data an object will store (called instance variables or fields)
-
What actions an object can perform (called methods)
Let’s create a simple Person class to understand the basics:
class Person {
// Instance variables (data the object stores)
String name;
int age;
double height;
// Methods (actions the object can perform)
void introduce() {
System.out.println("Hi, I'm " + name + " and I'm " + age + " years old.");
}
void celebrateBirthday() {
age = age + 1;
System.out.println("Happy birthday to me! I'm now " + age + " years old.");
}
}Try this in jshell:
jshell> class Person {
...> String name;
...> int age;
...> double height;
...>
...> void introduce() {
...> System.out.println("Hi, I'm " + name + " and I'm " + age + " years old.");
...> }
...>
...> void celebrateBirthday() {
...> age = age + 1;
...> System.out.println("Happy birthday to me! I'm now " + age + " years old.");
...> }
...> }
| created class PersonOnce you have a class, you can create objects (also called instances) from it. If the class is a blueprint, the object is the actual house built from that blueprint.
jshell> Person alice = new Person();
alice ==> Person@...
jshell> alice.name = "Alice";
alice.name ==> "Alice"
jshell> alice.age = 25;
alice.age ==> 25
jshell> alice.height = 5.6;
alice.height ==> 5.6
jshell> alice.introduce();
Hi, I'm Alice and I'm 25 years old.
jshell> alice.celebrateBirthday();
Happy birthday to me! I'm now 26 years old.You can create multiple objects from the same class:
jshell> Person bob = new Person();
bob ==> Person@...
jshell> bob.name = "Bob";
bob.name ==> "Bob"
jshell> bob.age = 30;
bob.age ==> 30
jshell> bob.introduce();
Hi, I'm Bob and I'm 30 years old.
jshell> alice.introduce();
Hi, I'm Alice and I'm 26 years old.Notice how alice and bob are separate objects with their own data, even
though they’re both created from the same Person class.
Instance variables (also called fields) are the data that each object stores. Each object gets its own copy of these variables.
In our Person class:
-
namestores the person’s name -
agestores the person’s age -
heightstores the person’s height
Each Person object has its own name, age, and height that can be different from
other Person objects.
Methods are the actions that objects can perform. Think of methods as functions that belong to a specific object. In Java, methods are where the computing happens! A programmer writes methods to make objects do what they need to do to accomplish some goal.
Methods are similar to functions in other programming languages, but with an important difference: they belong to a specific class and can access and modify that class’s instance variables.
In our Person class:
-
introduce()prints a greeting using the person’s name and age -
celebrateBirthday()increases the person’s age by 1
But there could be other things we add:
-
a method to change a person’s name or age.
-
add other methods to track more information about a person. (Like email address, cellphone number, etc.)
Methods can:
-
Access and modify instance variables (the variables inside each object)
-
Take parameters (input values)
-
Return values (the output or results of a computation)
-
Call other methods (ask other objects to do work for you)
Let’s look at a more practical example. Notice how there is a little bit of computation that happens based on the state of the object. (Well, you should not be able to take more money from an account than there is in the account!)
This kind of programming - where we add rules about what operations are allowed - is sometimes called implementing business rules. These are the real-world constraints that make our software behave correctly and safely.
class BankAccount {
String accountNumber;
String ownerName;
double balance;
void deposit(double amount) {
if (amount > 0) {
balance = balance + amount;
System.out.println("Deposited $" + amount + ". New balance: $" + balance);
} else {
System.out.println("Deposit amount must be positive.");
}
}
void withdraw(double amount) {
if (amount > 0 && amount <= balance) {
balance = balance - amount;
System.out.println("Withdrew $" + amount + ". New balance: $" + balance);
} else {
System.out.println("Invalid withdrawal amount.");
}
}
void checkBalance() {
System.out.println("Account " + accountNumber + " balance: $" + balance);
}
}Try using this class:
jshell> BankAccount account = new BankAccount();
account ==> BankAccount@...
jshell> account.accountNumber = "12345";
account.accountNumber ==> "12345"
jshell> account.ownerName = "Sarah";
account.ownerName ==> "Sarah"
jshell> account.balance = 100.0;
account.balance ==> 100.0
jshell> account.checkBalance();
Account 12345 balance: $100.0
jshell> account.deposit(50.0);
Deposited $50.0. New balance: $150.0
jshell> account.withdraw(25.0);
Withdrew $25.0. New balance: $125.0
jshell> account.withdraw(200.0);
Invalid withdrawal amount.With a class like this, you could create as many customer accounts as you need. Each account will have different values for different customers, and Java keeps all the data separate and correct.
Sometimes you want to set up an object with specific values when you create it. That’s what constructors do. A constructor is a special method that runs when you create a new object.
Constructors are always named the same as the class itself.
class Location {
String city;
String state;
int zipCode;
// Constructor
Location(String cityName, String stateName, int zip) {
city = cityName;
state = stateName;
zipCode = zip;
}
void displayLocation() {
System.out.println(city + ", " + state + " " + zipCode);
}
}Now you can create objects with initial values:
jshell> Location wilmington = new Location("Wilmington", "DE", 19801);
wilmington ==> Location@...
jshell> wilmington.displayLocation();
Wilmington, DE 19801
jshell> Location newark = new Location("Newark", "DE", 19711);
newark ==> Location@...
jshell> newark.displayLocation();
Newark, DE 19711Classes help you organize your code and model real-world concepts:
-
Organization: Keep related data and methods together
-
Reusability: Create multiple objects from the same class
-
Modularity: Each class handles its own responsibilities
-
Abstraction: Hide complex details behind simple interfaces
Methods can take input (parameters) and give back output (return values):
class Calculator {
String name;
Calculator(String calcName) {
name = calcName;
}
double add(double a, double b) {
return a + b;
}
double multiply(double a, double b) {
return a * b;
}
double divide(double a, double b) {
if (b != 0) {
return a / b;
} else {
System.out.println("Cannot divide by zero!");
return 0;
}
}
}jshell> Calculator calc = new Calculator("MyCalc");
calc ==> Calculator@...
jshell> double result = calc.add(5.0, 3.0);
result ==> 8.0
jshell> System.out.println("5 + 3 = " + result);
5 + 3 = 8.0
jshell> double product = calc.multiply(4.0, 7.0);
product ==> 28.0
jshell> double quotient = calc.divide(15.0, 3.0);
quotient ==> 5.0Remember the distinction:
- Class: The blueprint or template (like the Person class)
- Object: The actual instance created from the class (like alice and bob)
You write the class once, but you can create many objects from it.
Try creating these classes in jshell:
Exercise 1: Book Class
Create a Book class with:
- title, author, pages (instance variables)
- displayInfo() method that prints book details
- Constructor that sets all values
Exercise 2: Circle Class
Create a Circle class with:
- radius (instance variable)
- calculateArea() method that returns 3.14159 * radius * radius
- calculateCircumference() method that returns 2 * 3.14159 * radius
- Constructor that sets the radius
Exercise 3: Student Class
Create a Student class with:
- name, grade, studentId (instance variables)
- study() method that prints a study message
- takeTest() method that could change the grade
- Constructor to set initial values
-
Classes are blueprints that define what objects will look like and do
-
Objects are instances created from classes using the
newkeyword -
Instance variables store data unique to each object
-
Methods define what actions objects can perform
-
Constructors initialize objects when they’re created
-
You can create many objects from the same class
-
Each object has its own copy of instance variables
Classes are the foundation of object-oriented programming in Java. Once you understand classes, you can model almost anything in your programs - from simple concepts like numbers and strings to complex systems like games, databases, and web applications.