Classes and Objects
Learn how to create and use classes and objects in Java
Classes and Objects in Java
Welcome to the first lesson in the Object-Oriented Programming module! In this lesson, we'll explore the fundamental building blocks of OOP in Java: classes and objects.
What are Classes and Objects?
In object-oriented programming, a class is a blueprint for creating objects. It defines the properties (attributes) and behaviors (methods) that objects of that type will have. An object is an instance of a class - it's a concrete entity created from the class blueprint.
Think of a class as a cookie cutter, and the objects as the cookies made from that cutter.
Creating a Class in Java
Here's the basic syntax for defining a class in Java:
public class ClassName {
// Fields (attributes)
dataType fieldName1;
dataType fieldName2;
// Constructor
public ClassName() {
// initialization code
}
// Methods (behaviors)
returnType methodName1(parameters) {
// method body
}
returnType methodName2(parameters) {
// method body
}
}
Let's create a simple example of a Car
class:
public class Car {
// Fields
String make;
String model;
int year;
String color;
double fuelLevel;
// Constructor
public Car(String make, String model, int year, String color) {
this.make = make;
this.model = model;
this.year = year;
this.color = color;
this.fuelLevel = 100.0; // Full tank by default
}
// Methods
public void drive() {
System.out.println("The " + color + " " + make + " " + model + " is driving.");
fuelLevel -= 10;
}
public void refuel() {
System.out.println("Refueling the car.");
fuelLevel = 100.0;
}
public void displayInfo() {
System.out.println("Car Information:");
System.out.println("Make: " + make);
System.out.println("Model: " + model);
System.out.println("Year: " + year);
System.out.println("Color: " + color);
System.out.println("Fuel Level: " + fuelLevel + "%");
}
}
Creating and Using Objects
Once you've defined a class, you can create objects (instances of that class) using the new
keyword:
public class Main {
public static void main(String[] args) {
// Create a Car object
Car myCar = new Car("Toyota", "Camry", 2022, "Blue");
// Access object properties and methods
myCar.displayInfo();
System.out.println("\nTaking the car for a drive...");
myCar.drive();
System.out.println("\nUpdated car status:");
myCar.displayInfo();
System.out.println("\nRefueling the car...");
myCar.refuel();
System.out.println("\nFinal car status:");
myCar.displayInfo();
}
}
Output:
Car Information:
Make: Toyota
Model: Camry
Year: 2022
Color: Blue
Fuel Level: 100.0%
Taking the car for a drive...
The Blue Toyota Camry is driving.
Updated car status:
Car Information:
Make: Toyota
Model: Camry
Year: 2022
Color: Blue
Fuel Level: 90.0%
Refueling the car...
Refueling the car.
Final car status:
Car Information:
Make: Toyota
Model: Camry
Year: 2022
Color: Blue
Fuel Level: 100.0%
Key Components of a Class
1. Fields (Instance Variables)
Fields represent the state or attributes of an object. In our Car
example, make
, model
, year
, color
, and fuelLevel
are fields.
2. Constructors
Constructors are special methods used to initialize objects when they're created. They have the same name as the class and don't have a return type.
public Car(String make, String model, int year, String color) {
this.make = make;
this.model = model;
this.year = year;
this.color = color;
this.fuelLevel = 100.0;
}
The this
keyword refers to the current object, helping to distinguish between class fields and constructor parameters with the same name.
3. Methods
Methods define the behavior of objects. In our example, drive()
, refuel()
, and displayInfo()
are methods that define what a Car
object can do.
Access Modifiers
Access modifiers control the visibility of classes, fields, and methods:
- public: Accessible from any other class
- private: Accessible only within the same class
- protected: Accessible within the same class, subclasses, and classes in the same package
- default (no modifier): Accessible only within the same package
Encapsulation
Encapsulation is one of the core principles of OOP. It involves bundling the data (fields) and the methods that operate on the data into a single unit (class) and restricting direct access to the data.
Here's an improved version of our Car
class with proper encapsulation:
public class Car {
// Private fields
private String make;
private String model;
private int year;
private String color;
private double fuelLevel;
// Constructor
public Car(String make, String model, int year, String color) {
this.make = make;
this.model = model;
this.year = year;
this.color = color;
this.fuelLevel = 100.0;
}
// Getter methods
public String getMake() {
return make;
}
public String getModel() {
return model;
}
public int getYear() {
return year;
}
public String getColor() {
return color;
}
public double getFuelLevel() {
return fuelLevel;
}
// Setter methods
public void setColor(String color) {
this.color = color;
}
// Other methods
public void drive() {
System.out.println("The " + color + " " + make + " " + model + " is driving.");
fuelLevel -= 10;
}
public void refuel() {
System.out.println("Refueling the car.");
fuelLevel = 100.0;
}
public void displayInfo() {
System.out.println("Car Information:");
System.out.println("Make: " + make);
System.out.println("Model: " + model);
System.out.println("Year: " + year);
System.out.println("Color: " + color);
System.out.println("Fuel Level: " + fuelLevel + "%");
}
}
With this encapsulation, we've made the fields private and provided public getter methods to access them. We've also provided a setter method for color
since we might want to repaint the car, but not for other properties that typically shouldn't change after creation.
Practice Exercise
Create a Student
class with:
- Private fields for name, ID, grade level, and GPA
- A constructor to initialize these fields
- Getter methods for all fields
- Setter methods only for GPA (as other fields typically don't change)
- A method to display student information
- A method to check if the student is on the honor roll (GPA >= 3.5)
Then create a Main
class to demonstrate the use of the Student
class by creating multiple student objects and calling their methods.
Summary
In this lesson, you've learned:
- What classes and objects are in object-oriented programming
- How to define a class in Java with fields, constructors, and methods
- How to create and use objects
- The importance of encapsulation and how to implement it using access modifiers
- How to use getter and setter methods to control access to object data
Understanding classes and objects is fundamental to object-oriented programming in Java. In the next lessons, we'll explore more advanced OOP concepts like inheritance, polymorphism, and interfaces.