Skip to content

6.1. Defining Classes

A class is a blueprint for creating objects in Java. It defines the properties (attributes) and behaviors (methods) that objects of that class will possess.

Class Declaration Syntax

java
// Basic class declaration
[access-modifier] class ClassName {
    // Fields (attributes)
    // Constructors
    // Methods
}

Class Components

1. Fields (Attributes)

java
public class Student {
    // Instance variables (fields)
    private String name;
    private int age;
    private double gpa;

    // Static variable (class variable)
    private static int studentCount = 0;
}

2. Methods

java
public class Student {
    private String name;
    private int age;

    // Instance method
    public void displayInfo() {
        System.out.println("Name: " + name + ", Age: " + age);
    }

    // Method with parameters and return value
    public boolean isEligibleForScholarship(double minGPA) {
        // Implementation here
        return true;
    }
}

Complete Class Example

java
public class BankAccount {
    // Fields
    private String accountNumber;
    private String accountHolder;
    private double balance;

    // Constructor
    public BankAccount(String accountNumber, String accountHolder, double initialBalance) {
        this.accountNumber = accountNumber;
        this.accountHolder = accountHolder;
        this.balance = initialBalance;
    }

    // Methods
    public void deposit(double amount) {
        if (amount > 0) {
            balance += amount;
            System.out.println("Deposited: $" + amount);
        }
    }

    public void withdraw(double amount) {
        if (amount > 0 && amount <= balance) {
            balance -= amount;
            System.out.println("Withdrawn: $" + amount);
        }
    }

    public double getBalance() {
        return balance;
    }

    public void displayAccountInfo() {
        System.out.println("Account: " + accountNumber);
        System.out.println("Holder: " + accountHolder);
        System.out.println("Balance: $" + balance);
    }
}

Access Modifiers in Classes

  • public: Accessible from any other class
  • private: Accessible only within the same class
  • protected: Accessible within package and subclasses
  • Default (package-private): Accessible only within the same package

Object Creation

java
public class Main {
    public static void main(String[] args) {
        // Creating objects from class
        BankAccount account1 = new BankAccount("12345", "John Doe", 1000.0);
        BankAccount account2 = new BankAccount("67890", "Jane Smith", 500.0);

        // Using object methods
        account1.deposit(200.0);
        account1.displayAccountInfo();
    }
}