Classes and Objects in Java

Classes and Objects in Java

Classes are blueprints for creating objects, while objects are instances of classes. This is the foundation of object-oriented programming in Java.

Defining a Class

Person.java
public class Person {
    // Instance variables (attributes)
    private String name;
    private int age;
    private String email;
    
    // Constructor
    public Person(String name, int age, String email) {
        this.name = name;
        this.age = age;
        this.email = email;
    }
    
    // Instance methods (behaviors)
    public void introduce() {
        System.out.println("Hi, I'm " + name + " and I'm " + age + " years old.");
    }
    
    public void celebrateBirthday() {
        age++;
        System.out.println("Happy birthday " + name + "! Now " + age + " years old.");
    }
    
    // Getters and setters
    public String getName() {
        return name;
    }
    
    public void setName(String name) {
        this.name = name;
    }
    
    public int getAge() {
        return age;
    }
    
    public void setAge(int age) {
        this.age = age;
    }
    
    public String getEmail() {
        return email;
    }
    
    public void setEmail(String email) {
        this.email = email;
    }
    
    // Override toString method
    @Override
    public String toString() {
        return "Person{name='" + name + "', age=" + age + ", email='" + email + "'}";
    }
}

Creating and Using Objects

MainClass.java
public class MainClass {
    public static void main(String[] args) {
        // Creating objects (instances)
        Person person1 = new Person("John Doe", 25, "[email protected]");
        Person person2 = new Person("Jane Smith", 30, "[email protected]");
        
        // Using methods
        person1.introduce();
        person2.introduce();
        
        person1.celebrateBirthday();
        
        // Using getters and setters
        System.out.println("Person 1 name: " + person1.getName());
        person2.setAge(31);
        
        // Using toString
        System.out.println(person1);
        System.out.println(person2);
    }
}

Static Members

StaticExample.java
public class StaticExample {
    private static int count = 0; // Static variable
    private String instanceName; // Instance variable
    
    public StaticExample(String name) {
        this.instanceName = name;
        count++; // Increment static count
    }
    
    // Static method
    public static int getCount() {
        return count;
    }
    
    // Instance method
    public void display() {
        System.out.println(instanceName + " (Total objects: " + count + ")");
    }
    
    public static void main(String[] args) {
        System.out.println("Initial count: " + StaticExample.getCount());
        
        StaticExample obj1 = new StaticExample("Object 1");
        StaticExample obj2 = new StaticExample("Object 2");
        StaticExample obj3 = new StaticExample("Object 3");
        
        obj1.display();
        obj2.display();
        obj3.display();
        
        System.out.println("Final count: " + StaticExample.getCount());
    }
}

Encapsulation

BankAccount.java
public class BankAccount {
    private String accountNumber;
    private double balance;
    private String owner;
    
    public BankAccount(String accountNumber, String owner, double initialBalance) {
        this.accountNumber = accountNumber;
        this.owner = owner;
        this.balance = initialBalance;
    }
    
    // Public methods to access private data
    public void deposit(double amount) {
        if (amount > 0) {
            balance += amount;
            System.out.println("Deposited: $" + amount);
        } else {
            System.out.println("Invalid deposit amount");
        }
    }
    
    public void withdraw(double amount) {
        if (amount > 0 && amount <= balance) {
            balance -= amount;
            System.out.println("Withdrawn: $" + amount);
        } else {
            System.out.println("Invalid withdrawal amount or insufficient funds");
        }
    }
    
    public double getBalance() {
        return balance;
    }
    
    public String getAccountNumber() {
        return accountNumber;
    }
    
    public String getOwner() {
        return owner;
    }
}

Constructor Overloading

ConstructorOverloading.java
public class ConstructorOverloading {
    private String name;
    private int age;
    private String city;
    
    // Default constructor
    public ConstructorOverloading() {
        this.name = "Unknown";
        this.age = 0;
        this.city = "Unknown";
    }
    
    // Constructor with name only
    public ConstructorOverloading(String name) {
        this.name = name;
        this.age = 0;
        this.city = "Unknown";
    }
    
    // Constructor with name and age
    public ConstructorOverloading(String name, int age) {
        this.name = name;
        this.age = age;
        this.city = "Unknown";
    }
    
    // Constructor with all parameters
    public ConstructorOverloading(String name, int age, String city) {
        this.name = name;
        this.age = age;
        this.city = city;
    }
    
    public void display() {
        System.out.println("Name: " + name + ", Age: " + age + ", City: " + city);
    }
    
    public static void main(String[] args) {
        ConstructorOverloading obj1 = new ConstructorOverloading();
        ConstructorOverloading obj2 = new ConstructorOverloading("John");
        ConstructorOverloading obj3 = new ConstructorOverloading("Jane", 25);
        ConstructorOverloading obj4 = new ConstructorOverloading("Bob", 30, "New York");
        
        obj1.display();
        obj2.display();
        obj3.display();
        obj4.display();
    }
}
ℹ️
Encapsulation is achieved by making fields private and providing public getter/setter methods to control access.

Learn about arrays to work with collections of data.

Last updated on