Objects & Classes

Master Object-Oriented Programming fundamentals in Java.

📚 What are Classes and Objects?

Class

A class is a blueprint or template for creating objects. It defines the properties (attributes) and behaviors (methods) that objects of that class will have.

Think of it like: A class is like a cookie cutter - it defines the shape and structure, but it's not the cookie itself.

Basic Class Structure:

public class Student {
    // Instance variables (attributes/properties)
    String name;
    int rollNumber;
    double marks;
    
    // Constructor
    public Student(String n, int r, double m) {
        name = n;
        rollNumber = r;
        marks = m;
    }
    
    // Methods (behaviors)
    public void displayInfo() {
        System.out.println("Name: " + name);
        System.out.println("Roll Number: " + rollNumber);
        System.out.println("Marks: " + marks);
    }
    
    public double getPercentage() {
        return (marks / 500) * 100;
    }
}

Object

An object is an instance of a class. It's a concrete entity created from the class blueprint, with actual values for its attributes.

Think of it like: An object is the actual cookie made from the cookie cutter - it has real substance and can be used.

Creating and Using Objects:

public class Main {
    public static void main(String[] args) {
        // Creating objects (instantiation)
        Student student1 = new Student("Alice", 101, 450);
        Student student2 = new Student("Bob", 102, 380);
        
        // Using object methods
        student1.displayInfo();
        System.out.println("Percentage: " + student1.getPercentage() + "%");
        
        // Accessing object properties
        System.out.println(student2.name);  // Outputs: Bob
    }
}

🔑 Key Concepts

Constructors

A constructor is a special method that is called when an object is created. It initializes the object's attributes.

Types of Constructors:

public class Book {
    String title;
    String author;
    double price;
    
    // 1. Default Constructor (no parameters)
    public Book() {
        title = "Unknown";
        author = "Unknown";
        price = 0.0;
    }
    
    // 2. Parameterized Constructor
    public Book(String t, String a, double p) {
        title = t;
        author = a;
        price = p;
    }
    
    // 3. Constructor Overloading
    public Book(String t, String a) {
        title = t;
        author = a;
        price = 0.0;  // Default price
    }
}

Key Points: Constructor name must match class name. Constructors have no return type. Multiple constructors can exist (overloading).

Access Modifiers

Access modifiers control the visibility and accessibility of classes, methods, and variables.

public

Accessible from anywhere

private

Accessible only within the same class

protected

Accessible within package and subclasses

default (no modifier)

Accessible only within the same package

Example with Encapsulation:

public class BankAccount {
    // Private variables (encapsulation)
    private String accountNumber;
    private double balance;
    
    public BankAccount(String accNum, double initialBalance) {
        accountNumber = accNum;
        balance = initialBalance;
    }
    
    // Public getter methods
    public String getAccountNumber() {
        return accountNumber;
    }
    
    public double getBalance() {
        return balance;
    }
    
    // Public setter with validation
    public void deposit(double amount) {
        if (amount > 0) {
            balance += amount;
        }
    }
    
    public boolean withdraw(double amount) {
        if (amount > 0 && amount <= balance) {
            balance -= amount;
            return true;
        }
        return false;
    }
}

The 'this' Keyword

The this keyword refers to the current object instance.

public class Employee {
    private String name;
    private int id;
    
    // Using 'this' to distinguish between parameters and instance variables
    public Employee(String name, int id) {
        this.name = name;  // this.name refers to instance variable
        this.id = id;      // name and id are parameters
    }
    
    // Using 'this' to call another constructor
    public Employee(String name) {
        this(name, 0);  // Calls the parameterized constructor
    }
    
    public void display() {
        System.out.println("Name: " + this.name);
        System.out.println("ID: " + this.id);
    }
    
    // Using 'this' to return current object
    public Employee updateName(String name) {
        this.name = name;
        return this;  // Method chaining
    }
}

Static Members

Static members belong to the class itself, not to any specific object. They are shared across all instances.

public class Counter {
    // Static variable - shared by all objects
    private static int count = 0;
    
    // Instance variable - unique to each object
    private int instanceId;
    
    public Counter() {
        count++;  // Increment shared counter
        instanceId = count;
    }
    
    // Static method - can be called without creating an object
    public static int getCount() {
        return count;
        // Note: Cannot access instanceId here (non-static)
    }
    
    public int getInstanceId() {
        return instanceId;
    }
}

// Usage:
Counter c1 = new Counter();
Counter c2 = new Counter();
Counter c3 = new Counter();

System.out.println(Counter.getCount());  // Outputs: 3 (called on class)
System.out.println(c1.getInstanceId());  // Outputs: 1
System.out.println(c2.getInstanceId());  // Outputs: 2

Remember: Static methods can only access static variables and call other static methods directly. They cannot use 'this' keyword.

💡 Complete Examples

Example 1: Rectangle Class

A simple class to represent a rectangle with methods to calculate area and perimeter.

public class Rectangle {
    // Instance variables
    private double length;
    private double width;
    
    // Constructor
    public Rectangle(double l, double w) {
        length = l;
        width = w;
    }
    
    // Method to calculate area
    public double calculateArea() {
        return length * width;
    }
    
    // Method to calculate perimeter
    public double calculatePerimeter() {
        return 2 * (length + width);
    }
    
    // Getter methods
    public double getLength() {
        return length;
    }
    
    public double getWidth() {
        return width;
    }
    
    // Setter methods with validation
    public void setLength(double l) {
        if (l > 0) {
            length = l;
        }
    }
    
    public void setWidth(double w) {
        if (w > 0) {
            width = w;
        }
    }
}

// Usage:
Rectangle rect = new Rectangle(5.0, 3.0);
System.out.println("Area: " + rect.calculateArea());        // 15.0
System.out.println("Perimeter: " + rect.calculatePerimeter()); // 16.0

Example 2: Library Book System

A more complex example with multiple concepts combined.

public class LibraryBook {
    // Static variable to track total books
    private static int totalBooks = 0;
    
    // Instance variables
    private String title;
    private String author;
    private String isbn;
    private boolean isIssued;
    
    // Constructor
    public LibraryBook(String title, String author, String isbn) {
        this.title = title;
        this.author = author;
        this.isbn = isbn;
        this.isIssued = false;
        totalBooks++;
    }
    
    // Method to issue book
    public boolean issueBook() {
        if (!isIssued) {
            isIssued = true;
            return true;
        }
        return false;
    }
    
    // Method to return book
    public void returnBook() {
        isIssued = false;
    }
    
    // Check availability
    public boolean isAvailable() {
        return !isIssued;
    }
    
    // Display book information
    public void displayInfo() {
        System.out.println("Title: " + title);
        System.out.println("Author: " + author);
        System.out.println("ISBN: " + isbn);
        System.out.println("Status: " + (isIssued ? "Issued" : "Available"));
    }
    
    // Static method to get total books
    public static int getTotalBooks() {
        return totalBooks;
    }
}

// Usage:
LibraryBook book1 = new LibraryBook("Java Programming", "John Doe", "123-456");
LibraryBook book2 = new LibraryBook("Data Structures", "Jane Smith", "789-012");

book1.issueBook();
book1.displayInfo();

System.out.println("Total books in library: " + LibraryBook.getTotalBooks());

Example 3: Time Class

Demonstrates constructor overloading and method chaining.

public class Time {
    private int hours;
    private int minutes;
    private int seconds;
    
    // Default constructor
    public Time() {
        this(0, 0, 0);
    }
    
    // Constructor with hours and minutes
    public Time(int h, int m) {
        this(h, m, 0);
    }
    
    // Full constructor
    public Time(int h, int m, int s) {
        setTime(h, m, s);
    }
    
    // Set time with validation
    public void setTime(int h, int m, int s) {
        hours = (h >= 0 && h < 24) ? h : 0;
        minutes = (m >= 0 && m < 60) ? m : 0;
        seconds = (s >= 0 && s < 60) ? s : 0;
    }
    
    // Add seconds
    public void addSeconds(int s) {
        seconds += s;
        minutes += seconds / 60;
        seconds %= 60;
        hours += minutes / 60;
        minutes %= 60;
        hours %= 24;
    }
    
    // Display in 24-hour format
    public String toString() {
        return String.format("%02d:%02d:%02d", hours, minutes, seconds);
    }
}

// Usage:
Time t1 = new Time();           // 00:00:00
Time t2 = new Time(14, 30);     // 14:30:00
Time t3 = new Time(9, 15, 45);  // 09:15:45

t3.addSeconds(20);
System.out.println(t3);  // 09:16:05

📝 Practice Questions

📋 Quick Reference

Concept Description Example
Class Blueprint for objects class Car { }
Object Instance of a class Car myCar = new Car();
Constructor Initializes objects public Car() { }
this Refers to current object this.name = name;
static Belongs to class, not object static int count;
Encapsulation Data hiding with private + getters/setters private int age;