Introduction
Java is a powerful object-oriented programming language. At its core, Java revolves around classes and objects, which are essential for creating and managing real-world entities in a program. Understanding classes and objects is crucial for mastering Java programming.
What Are Classes in Java?
A class in Java serves as a blueprint or template for creating objects. It defines the properties (fields) and behaviors (methods) that objects of the class will have.
- Fields: These are variables within a class that hold data.
- Methods: These are functions that define actions or behaviors of the class.
Syntax of a Class
class ClassName {
// Fields (variables)
dataType fieldName;
// Methods
returnType methodName() {
// Method body
}
}
Example: Defining a Class
class Car {
// Fields
String brand;
int year;
// Method
void displayDetails() {
System.out.println("Brand: " + brand + ", Year: " + year);
}
}
In this example:
- Car is the class name.
- brand and year are fields.
- displayDetails() is a method that displays the car’s details.
What Are Objects in Java?
An object is an instance of a class. It represents a real-world entity and contains state (field values) and behavior (method actions). Objects are created using the new
keyword.
Creating an Object
ClassName objectName = new ClassName();
Example: Creating and Using an Object
public class Main {
public static void main(String[] args) {
Car myCar = new Car(); // Creating an object
myCar.brand = "Toyota"; // Assigning values to fields
myCar.year = 2022;
myCar.displayDetails(); // Calling the method
}
}
Output:
Brand: Toyota, Year: 2022
Key Differences Between Classes and Objects
Class | Object |
---|---|
Blueprint for creating objects | Instance of a class |
Does not occupy memory | Occupies memory when created |
Defines properties and methods | Contains actual data and behavior |
Features of Java Classes and Objects
- Encapsulation: Combine data and behavior into a single unit (class).
- Reusability: A class can be reused to create multiple objects.
- Abstraction: Hide implementation details and expose only functionality.
Practical Examples of Classes and Objects
Example 1: Bank Account
class BankAccount {
String accountHolder;
double balance;
void deposit(double amount) {
balance += amount;
}
void withdraw(double amount) {
if (amount <= balance) {
balance -= amount;
} else {
System.out.println("Insufficient balance.");
}
}
void displayBalance() {
System.out.println("Account Holder: " + accountHolder);
System.out.println("Balance: " + balance);
}
}
public class Main {
public static void main(String[] args) {
BankAccount account = new BankAccount();
account.accountHolder = "Alice";
account.balance = 5000;
account.deposit(2000);
account.withdraw(3000);
account.displayBalance();
}
}
Output:
Account Holder: Alice
Balance: 4000.0
Example 2: Student Details
class Student {
String name;
int age;
void displayInfo() {
System.out.println("Name: " + name);
System.out.println("Age: " + age);
}
}
public class Main {
public static void main(String[] args) {
Student student = new Student();
student.name = "John";
student.age = 20;
student.displayInfo();
}
}
Output:
Name: John
Age: 20
Benefits of Using Classes and Objects in Java
- Modularity: Code is organized into reusable units (classes).
- Flexibility: Objects make it easier to adapt code for new requirements.
- Scalability: Large programs can be developed by breaking them into smaller classes.
- Reusability: Classes can be reused in different programs.
Common Mistakes to Avoid
Not initializing objects: Always initialize objects using the new keyword.
Car car; // Declared but not initialized
car.brand = "BMW"; // This will throw an error
Accessing private fields directly: Use getters and setters to access private fields.
Advanced Concepts Related to Classes and Objects
Constructors
A constructor is a special method used to initialize objects. It has the same name as the class and does not have a return type.
Example:
class Car {
String brand;
// Constructor
Car(String carBrand) {
brand = carBrand;
}
void displayBrand() {
System.out.println("Brand: " + brand);
}
}
public class Main {
public static void main(String[] args) {
Car myCar = new Car("Honda");
myCar.displayBrand();
}
}
Output:
Brand: Honda
Static Members
Static fields and methods belong to the class rather than objects.
Example:
class MathUtils {
static int square(int num) {
return num * num;
}
}
public class Main {
public static void main(String[] args) {
System.out.println("Square of 5: " + MathUtils.square(5));
}
}
Output:
Square of 5: 25