Java Classes and Objects

In Java, classes and objects are the core units of object-oriented programming. A class defines the structure and behavior, while an object is a concrete instance of that class. Understanding how to create and use classes and objects is essential to writing real Java programs.

What is a Class?

A class is a user-defined blueprint from which objects are created. It defines:

  • Fields (attributes): Variables that store the state/data of an object.
  • Methods (behaviors): Functions that define what an object can do.

Defining a class does not create any object or allocate any memory — it simply describes the structure.

Syntax

class ClassName {
    // fields
    dataType fieldName;

    // methods
    returnType methodName() {
        // body
    }
}

Example – Defining a Class

class BankAccount {
    String accountHolder;
    double balance;

    void deposit(double amount) {
        balance += amount;
        System.out.println("Deposited: " + amount);
    }

    void showBalance() {
        System.out.println("Balance: " + balance);
    }
}

What is an Object?

An object is an instance of a class. Creating an object is called instantiation. Each object gets its own copy of the class's fields.

Creating an Object

ClassName objectName = new ClassName();

The new keyword allocates memory for the object and calls the constructor to initialize it.

Example – Creating Objects

public class Main {
    public static void main(String[] args) {
        BankAccount account1 = new BankAccount();
        account1.accountHolder = "Alice";
        account1.balance = 0;
        account1.deposit(500);
        account1.showBalance();

        BankAccount account2 = new BankAccount();
        account2.accountHolder = "Bob";
        account2.balance = 200;
        account2.deposit(300);
        account2.showBalance();
    }
}

Output:

Deposited: 500.0
Balance: 500.0
Deposited: 300.0
Balance: 500.0

Each object (account1 and account2) maintains its own separate balance and accountHolder — they do not interfere with each other.

Accessing Fields and Methods

Fields and methods of an object are accessed using the dot operator (.):

objectName.fieldName         // access a field
objectName.methodName()      // call a method

Class with Multiple Objects

class Student {
    String name;
    int rollNo;
    int marks;

    void displayInfo() {
        System.out.println("Name: " + name);
        System.out.println("Roll No: " + rollNo);
        System.out.println("Marks: " + marks);
        System.out.println("---");
    }
}

public class School {
    public static void main(String[] args) {
        Student s1 = new Student();
        s1.name = "Priya";
        s1.rollNo = 101;
        s1.marks = 88;

        Student s2 = new Student();
        s2.name = "Ravi";
        s2.rollNo = 102;
        s2.marks = 76;

        s1.displayInfo();
        s2.displayInfo();
    }
}

Output:

Name: Priya
Roll No: 101
Marks: 88
---
Name: Ravi
Roll No: 102
Marks: 76
---

null Reference

Before a reference variable is assigned an object, it holds the value null, meaning it points to nothing. Trying to access a field or method on a null reference causes a NullPointerException.

Student s = null;
// s.displayInfo(); // This would throw NullPointerException

Objects as Method Parameters

Objects can be passed to methods, allowing methods to work with or modify objects.

static void printStudentName(Student student) {
    System.out.println("Student: " + student.name);
}

// In main:
Student s = new Student();
s.name = "Anjali";
printStudentName(s);   // Student: Anjali

Objects as Return Types

A method can also return an object.

static Student createStudent(String name, int roll, int marks) {
    Student s = new Student();
    s.name = name;
    s.rollNo = roll;
    s.marks = marks;
    return s;
}

// In main:
Student s = createStudent("Mehta", 105, 92);
s.displayInfo();

Anonymous Objects

An anonymous object is created and used immediately without being stored in a reference variable. It is used when the object is needed only once.

new Student().displayInfo();   // object created and used in one line

Memory – Stack vs Heap

  • Reference variable (e.g., Student s1) is stored on the stack.
  • The actual object (field values and method data) is stored on the heap.
  • The reference variable holds the memory address of the object on the heap.

Summary

  • A class is a blueprint that defines fields and methods.
  • An object is an instance of a class, created using the new keyword.
  • Each object has its own copy of the class's fields.
  • Fields and methods are accessed using the dot operator (.).
  • Multiple objects can be created from the same class, each with different data.
  • Objects can be passed to methods and returned from methods.

Leave a Comment

Your email address will not be published. Required fields are marked *