TutorialsJavaClasses & Objects
Share:

Classes & Objects

beginner

Part of Java Basics

Theory

Java is fundamentally an object-oriented language. Everything in Java revolves around classes and objects. A class is a blueprint or template, and an object is an instance of that class.

Class Definition

A class defines the state (fields/variables) and behavior (methods) of an object:

public class Car {
    // Fields (state)
    String brand;
    String model;
    int year;
 
    // Methods (behavior)
    void start() {
        System.out.println("The car is starting...");
    }
}

Fields (Instance Variables)

Fields represent the data or state of an object. Each object created from the class gets its own copy of these fields:

public class Student {
    String name;        // instance variable
    int age;            // instance variable
    double gpa;         // instance variable
    static int count;   // class variable (shared across all instances)
}

Constructors

A constructor is a special method that is called when an object is created. It initializes the object's state. Constructors have the same name as the class and no return type.

Default Constructor — If you don't define any constructor, Java provides a no-argument default constructor that sets numeric fields to 0, booleans to false, and objects to null.

Parameterized Constructor — A constructor that accepts parameters to initialize fields:

public class Book {
    String title;
    String author;
    int pages;
 
    // Default constructor
    public Book() {
        this.title = "Unknown";
        this.author = "Unknown";
        this.pages = 0;
    }
 
    // Parameterized constructor
    public Book(String title, String author, int pages) {
        this.title = title;
        this.author = author;
        this.pages = pages;
    }
}

The this Keyword

this refers to the current object instance. It is used to:

  • Distinguish instance variables from parameters with the same name
  • Call another constructor (this())
  • Pass the current object as an argument

Creating Objects with new

Objects are created using the new keyword followed by a constructor call:

Book myBook = new Book("1984", "George Orwell", 328);
Book emptyBook = new Book(); // Uses default constructor

new allocates memory for the object on the heap and returns a reference.

Access Modifiers

Access modifiers control the visibility of classes, methods, and fields:

| Modifier | Class | Package | Subclass | World | |----------|-------|---------|----------|-------| | public | ✓ | ✓ | ✓ | ✓ | | protected | ✓ | ✓ | ✓ | ✗ | | default (no modifier) | ✓ | ✓ | ✗ | ✗ | | private | ✓ | ✗ | ✗ | ✗ |

public class Person {
    private String name;      // accessible only within this class
    protected int age;        // accessible in package + subclasses
    String address;           // default: accessible in package
    public String email;      // accessible everywhere
}

Getters and Setters (Encapsulation)

Encapsulation is the practice of hiding internal data and providing controlled access through public methods:

public class BankAccount {
    private String accountNumber;
    private double balance;
 
    // Getter
    public double getBalance() {
        return balance;
    }
 
    // Setter with validation
    public void setBalance(double balance) {
        if (balance >= 0) {
            this.balance = balance;
        } else {
            System.out.println("Balance cannot be negative");
        }
    }
 
    public void deposit(double amount) {
        if (amount > 0) {
            this.balance += amount;
        }
    }
}

Static Members

static members belong to the class itself, not to individual instances:

public class MathUtils {
    public static final double PI = 3.14159;
 
    public static int add(int a, int b) {
        return a + b;
    }
 
    private static int instanceCount = 0;
 
    public MathUtils() {
        instanceCount++;
    }
 
    public static int getInstanceCount() {
        return instanceCount;
    }
}
 
// Usage:
int sum = MathUtils.add(5, 3);          // No object needed
System.out.println(MathUtils.PI);        // Access static field

The toString() Method

toString() returns a string representation of an object. By default, it returns the class name + hash code. Override it to provide meaningful output:

@Override
public String toString() {
    return "Student{name='" + name + "', age=" + age + ", gpa=" + gpa + "}";
}

Always override toString() in your classes for easier debugging. Most IDEs can generate it automatically.

Practical Examples

Example 1: Complete Class with Encapsulation
java
Example 2: Multiple Constructors and this()
java

Use this() to call one constructor from another. This avoids code duplication and keeps initialization logic in one place.

Exercises

Create a Dog Class

easy

Create a Dog class with fields: name (String), breed (String), and age (int). Add a constructor, getters and setters, and a bark() method that prints 'Woof! My name is [name].' Also override toString().

Expected Output:

Creating a Dog named 'Buddy' (Golden Retriever, age 3) and calling bark() prints: Woof! My name is Buddy.

Library Book System

medium

Create a Book class with private fields: isbn, title, author, isCheckedOut. Add methods: checkOut(), returnBook(), isAvailable(). Add a static field totalBooks that increments with each Book created.

Expected Output:

Two Book objects created. totalBooks is 2. Checking out one book makes it unavailable. Returning it makes it available again.

Bank Account with Transaction History

hard

Create a BankAccount class with: accountNumber, accountHolder, balance, and a transaction history (use a String array or ArrayList). Add methods: deposit(amount), withdraw(amount), getTransactionHistory(), and transferTo(otherAccount, amount).

Expected Output:

Creating two accounts, depositing money, withdrawing, and transferring between them. printStatement shows a chronological list of all transactions.

Mini Quiz

Mini Quiz

Mini Project

Mini Project: Student Management System

Create a Student class and a Course class that work together. Students can enroll in courses, drop courses, and view their schedule. The system should track enrolled students per course and prevent duplicate enrollments.

Requirements:

    Bonus Challenge

    Add a Transcript class that stores grades (A, B, C, etc.) for each completed course. Add a GPA calculation method.