Introduction
Imagine you're an architect designing houses. The blueprint (class) defines what a house should have - rooms, doors, windows. The actual houses (objects) built from that blueprint are the real things you can live in. That's exactly how classes and objects work in Java!
Classes are templates that define the structure and behavior, while objects are actual instances created from those templates. This is the foundation of Object-Oriented Programming (OOP) in Java.
What are Classes and Objects?
Class:
- β Blueprint/template for creating objects
- β Defines attributes (fields) and behaviors (methods)
- β Logical entity that doesn't occupy memory
Object:
- β Instance of a class
- β Physical entity that occupies memory
- β Has state (data) and behavior (methods)
- β
Created using the
newkeyword
Code Explanation with Examples
Example 1: Basic Class and Object Creation
// π― CLASS DEFINITION: The blueprint
class Car {
// π― ATTRIBUTES (Fields/Instance Variables)
String brand;
String color;
int year;
double price;
boolean isRunning;
// π― CONSTRUCTOR: Special method to initialize objects
public Car(String brand, String color, int year, double price) {
this.brand = brand;
this.color = color;
this.year = year;
this.price = price;
this.isRunning = false; // Default value
}
// π― BEHAVIORS (Methods)
public void startEngine() {
if (!isRunning) {
isRunning = true;
System.out.println(brand + " engine started! Vroom vroom! π");
} else {
System.out.println(brand + " engine is already running!");
}
}
public void stopEngine() {
if (isRunning) {
isRunning = false;
System.out.println(brand + " engine stopped.");
} else {
System.out.println(brand + " engine is already stopped.");
}
}
public void displayInfo() {
System.out.println("=== CAR INFORMATION ===");
System.out.println("Brand: " + brand);
System.out.println("Color: " + color);
System.out.println("Year: " + year);
System.out.println("Price: $" + price);
System.out.println("Engine: " + (isRunning ? "Running" : "Stopped"));
}
// π― Method with return value
public double calculateDepreciation(int currentYear) {
int age = currentYear - year;
return price * (1 - (age * 0.1)); // 10% depreciation per year
}
}
// π― MAIN CLASS to demonstrate object creation
public class BasicClassObject {
public static void main(String[] args) {
System.out.println("=== BASIC CLASS AND OBJECT CREATION ===");
// π― OBJECT CREATION: Using 'new' keyword
Car car1 = new Car("Toyota", "Red", 2020, 25000.0);
Car car2 = new Car("Honda", "Blue", 2022, 30000.0);
Car car3 = new Car("Ford", "Black", 2018, 20000.0);
// π― ACCESSING OBJECT PROPERTIES AND BEHAVIORS
System.out.println("\n1. ACCESSING OBJECT PROPERTIES:");
System.out.println("Car1 brand: " + car1.brand);
System.out.println("Car2 color: " + car2.color);
System.out.println("Car3 year: " + car3.year);
// π― CALLING OBJECT METHODS
System.out.println("\n2. CALLING OBJECT METHODS:");
car1.displayInfo();
car2.displayInfo();
car3.displayInfo();
// π― INTERACTING WITH OBJECTS
System.out.println("\n3. OBJECT INTERACTION:");
car1.startEngine();
car2.startEngine();
car1.stopEngine();
// π― METHODS WITH RETURN VALUES
System.out.println("\n4. METHODS WITH RETURN VALUES:");
double car1Value = car1.calculateDepreciation(2024);
double car2Value = car2.calculateDepreciation(2024);
System.out.println("Car1 current value: $" + car1Value);
System.out.println("Car2 current value: $" + car2Value);
// π― MODIFYING OBJECT STATE
System.out.println("\n5. MODIFYING OBJECT STATE:");
System.out.println("Before modification - Car1 color: " + car1.color);
car1.color = "Green"; // Direct field access
System.out.println("After modification - Car1 color: " + car1.color);
// π― OBJECT IDENTITY AND MEMORY
System.out.println("\n6. OBJECT IDENTITY:");
System.out.println("car1 == car2: " + (car1 == car2));
System.out.println("car1 hashCode: " + car1.hashCode());
System.out.println("car2 hashCode: " + car2.hashCode());
// π― ARRAY OF OBJECTS
System.out.println("\n7. ARRAY OF OBJECTS:");
Car[] cars = {car1, car2, car3};
for (Car car : cars) {
car.displayInfo();
System.out.println("---");
}
}
}
Output:
=== BASIC CLASS AND OBJECT CREATION === 1. ACCESSING OBJECT PROPERTIES: Car1 brand: Toyota Car2 color: Blue Car3 year: 2018 2. CALLING OBJECT METHODS: === CAR INFORMATION === Brand: Toyota Color: Red Year: 2020 Price: $25000.0 Engine: Stopped === CAR INFORMATION === Brand: Honda Color: Blue Year: 2022 Price: $30000.0 Engine: Stopped === CAR INFORMATION === Brand: Ford Color: Black Year: 2018 Price: $20000.0 Engine: Stopped 3. OBJECT INTERACTION: Toyota engine started! Vroom vroom! π Honda engine started! Vroom vroom! π Toyota engine stopped. 4. METHODS WITH RETURN VALUES: Car1 current value: $19000.0 Car2 current value: $29400.0 5. MODIFYING OBJECT STATE: Before modification - Car1 color: Red After modification - Car1 color: Green 6. OBJECT IDENTITY: car1 == car2: false car1 hashCode: 1324119927 car2 hashCode: 990368553 7. ARRAY OF OBJECTS: === CAR INFORMATION === Brand: Toyota Color: Green Year: 2020 Price: $25000.0 Engine: Stopped --- === CAR INFORMATION === Brand: Honda Color: Blue Year: 2022 Price: $30000.0 Engine: Running --- === CAR INFORMATION === Brand: Ford Color: Black Year: 2018 Price: $20000.0 Engine: Stopped ---
Example 2: Constructors and Method Overloading
// π― CLASS WITH MULTIPLE CONSTRUCTORS
class Student {
// π― ATTRIBUTES
String name;
int age;
String studentId;
double gpa;
String major;
// π― CONSTRUCTOR 1: Default constructor (no parameters)
public Student() {
this.name = "Unknown";
this.age = 0;
this.studentId = "N/A";
this.gpa = 0.0;
this.major = "Undeclared";
System.out.println("Default constructor called - Student created with default values");
}
// π― CONSTRUCTOR 2: Parameterized constructor (basic info)
public Student(String name, int age, String studentId) {
this.name = name;
this.age = age;
this.studentId = studentId;
this.gpa = 0.0;
this.major = "Undeclared";
System.out.println("Basic constructor called - Student: " + name);
}
// π― CONSTRUCTOR 3: Parameterized constructor (full info)
public Student(String name, int age, String studentId, double gpa, String major) {
this.name = name;
this.age = age;
this.studentId = studentId;
this.gpa = gpa;
this.major = major;
System.out.println("Full constructor called - Student: " + name + ", Major: " + major);
}
// π― CONSTRUCTOR 4: Copy constructor
public Student(Student other) {
this.name = other.name;
this.age = other.age;
this.studentId = other.studentId;
this.gpa = other.gpa;
this.major = other.major;
System.out.println("Copy constructor called - Copied student: " + other.name);
}
// π― METHODS WITH OVERLOADING (same name, different parameters)
// Method 1: Basic study method
public void study() {
System.out.println(name + " is studying generally.");
}
// Method 2: Overloaded study method with subject
public void study(String subject) {
System.out.println(name + " is studying " + subject + ".");
}
// Method 3: Overloaded study method with subject and hours
public void study(String subject, int hours) {
System.out.println(name + " is studying " + subject + " for " + hours + " hours.");
// Increase GPA based on study hours
this.gpa += hours * 0.01;
}
// π― DISPLAY METHODS
public void displayInfo() {
System.out.println("=== STUDENT INFO ===");
System.out.println("Name: " + name);
System.out.println("Age: " + age);
System.out.println("ID: " + studentId);
System.out.println("GPA: " + gpa);
System.out.println("Major: " + major);
}
public void displayInfo(boolean detailed) {
if (detailed) {
System.out.println("=== DETAILED STUDENT INFO ===");
System.out.println("Name: " + name);
System.out.println("Age: " + age + " years old");
System.out.println("Student ID: " + studentId);
System.out.println("GPA: " + String.format("%.2f", gpa));
System.out.println("Major: " + major);
System.out.println("Status: " + (gpa > 3.0 ? "Excellent" : "Good"));
} else {
displayInfo();
}
}
// π― STATIC METHOD (belongs to class, not object)
public static void displayUniversity() {
System.out.println("University: Java State University");
}
}
// π― MAIN CLASS
public class ConstructorsAndOverloading {
public static void main(String[] args) {
System.out.println("=== CONSTRUCTORS AND METHOD OVERLOADING ===");
// π― CREATING OBJECTS USING DIFFERENT CONSTRUCTORS
System.out.println("\n1. OBJECT CREATION WITH DIFFERENT CONSTRUCTORS:");
// Using default constructor
Student student1 = new Student();
student1.displayInfo();
// Using basic constructor
Student student2 = new Student("Alice Johnson", 20, "S12345");
student2.displayInfo();
// Using full constructor
Student student3 = new Student("Bob Smith", 22, "S67890", 3.8, "Computer Science");
student3.displayInfo();
// Using copy constructor
Student student4 = new Student(student3);
student4.displayInfo();
// π― METHOD OVERLOADING DEMONSTRATION
System.out.println("\n2. METHOD OVERLOADING DEMONSTRATION:");
student1.study();
student2.study("Mathematics");
student3.study("Programming", 3);
// Display methods with overloading
student3.displayInfo(false);
student3.displayInfo(true);
// π― STATIC METHOD CALL (Class-level, not object-level)
System.out.println("\n3. STATIC METHOD CALL:");
Student.displayUniversity();
// π― OBJECT COMPARISON AND MODIFICATION
System.out.println("\n4. OBJECT COMPARISON:");
System.out.println("student3 == student4: " + (student3 == student4));
System.out.println("student3 name == student4 name: " + student3.name.equals(student4.name));
// Modify copied object
student4.name = "Robert Smith";
student4.gpa = 3.5;
System.out.println("\nAfter modifying student4:");
student3.displayInfo();
student4.displayInfo();
// π― NULL OBJECTS AND OBJECT CREATION
System.out.println("\n5. NULL OBJECTS:");
Student nullStudent = null;
System.out.println("nullStudent: " + nullStudent);
// This would cause NullPointerException:
// nullStudent.displayInfo();
// Safe object creation
if (nullStudent == null) {
nullStudent = new Student("New Student", 19, "S99999");
nullStudent.displayInfo();
}
// π― OBJECT LIFECYCLE DEMONSTRATION
System.out.println("\n6. OBJECT LIFECYCLE:");
demonstrateObjectLifecycle();
}
public static void demonstrateObjectLifecycle() {
System.out.println("Creating temporary student object...");
Student tempStudent = new Student("Temporary", 25, "TEMP001");
tempStudent.study("Java", 5);
System.out.println("Temporary student GPA: " + tempStudent.gpa);
System.out.println("Method ending - object becomes eligible for garbage collection");
}
}
Output:
=== CONSTRUCTORS AND METHOD OVERLOADING === 1. OBJECT CREATION WITH DIFFERENT CONSTRUCTORS: Default constructor called - Student created with default values === STUDENT INFO === Name: Unknown Age: 0 ID: N/A GPA: 0.0 Major: Undeclared Basic constructor called - Student: Alice Johnson === STUDENT INFO === Name: Alice Johnson Age: 20 ID: S12345 GPA: 0.0 Major: Undeclared Full constructor called - Student: Bob Smith, Major: Computer Science === STUDENT INFO === Name: Bob Smith Age: 22 ID: S67890 GPA: 3.8 Major: Computer Science Copy constructor called - Copied student: Bob Smith === STUDENT INFO === Name: Bob Smith Age: 22 ID: S67890 GPA: 3.8 Major: Computer Science 2. METHOD OVERLOADING DEMONSTRATION: Unknown is studying generally. Alice Johnson is studying Mathematics. Bob Smith is studying Programming for 3 hours. === STUDENT INFO === Name: Bob Smith Age: 22 ID: S67890 GPA: 3.83 Major: Computer Science === DETAILED STUDENT INFO === Name: Bob Smith Age: 22 years old Student ID: S67890 GPA: 3.83 Major: Computer Science Status: Excellent 3. STATIC METHOD CALL: University: Java State University 4. OBJECT COMPARISON: student3 == student4: false student3 name == student4 name: true After modifying student4: === STUDENT INFO === Name: Bob Smith Age: 22 ID: S67890 GPA: 3.83 Major: Computer Science === STUDENT INFO === Name: Robert Smith Age: 22 ID: S67890 GPA: 3.5 Major: Computer Science 5. NULL OBJECTS: nullStudent: null Basic constructor called - Student: New Student === STUDENT INFO === Name: New Student Age: 19 ID: S99999 GPA: 0.0 Major: Undeclared 6. OBJECT LIFECYCLE: Creating temporary student object... Basic constructor called - Student: Temporary Temporary is studying Java for 5 hours. Temporary student GPA: 0.05 Method ending - object becomes eligible for garbage collection
Example 3: Real-World Bank Account System
// π― BANK ACCOUNT CLASS
class BankAccount {
// π― ATTRIBUTES (Encapsulated with private access)
private String accountNumber;
private String accountHolder;
private double balance;
private String accountType;
private boolean isActive;
private static int totalAccounts = 0; // Class variable
// π― CONSTRUCTORS
public BankAccount(String accountHolder, String accountType, double initialDeposit) {
this.accountNumber = generateAccountNumber();
this.accountHolder = accountHolder;
this.accountType = accountType;
this.balance = initialDeposit;
this.isActive = true;
totalAccounts++;
System.out.println("β
Account created: " + accountNumber + " for " + accountHolder);
}
// π― BUSINESS METHODS
public void deposit(double amount) {
if (isActive && amount > 0) {
balance += amount;
System.out.println("π° Deposited: $" + amount + " to " + accountNumber);
System.out.println(" New balance: $" + balance);
} else {
System.out.println("β Deposit failed: Invalid amount or inactive account");
}
}
public boolean withdraw(double amount) {
if (isActive && amount > 0 && amount <= balance) {
balance -= amount;
System.out.println("πΈ Withdrawn: $" + amount + " from " + accountNumber);
System.out.println(" Remaining balance: $" + balance);
return true;
} else {
System.out.println("β Withdrawal failed: Insufficient funds or invalid amount");
return false;
}
}
public void transfer(BankAccount recipient, double amount) {
if (this.withdraw(amount)) {
recipient.deposit(amount);
System.out.println("π Transfer completed: $" + amount + " to " + recipient.getAccountNumber());
} else {
System.out.println("β Transfer failed");
}
}
// π― GETTER METHODS (Accessors)
public double getBalance() {
return balance;
}
public String getAccountNumber() {
return accountNumber;
}
public String getAccountHolder() {
return accountHolder;
}
public String getAccountType() {
return accountType;
}
public boolean isActive() {
return isActive;
}
// π― SETTER METHODS (Mutators) with validation
public void setAccountHolder(String newHolder) {
if (newHolder != null && !newHolder.trim().isEmpty()) {
String oldHolder = this.accountHolder;
this.accountHolder = newHolder;
System.out.println("βοΈ Account holder changed from '" + oldHolder + "' to '" + newHolder + "'");
}
}
public void deactivateAccount() {
if (isActive) {
isActive = false;
System.out.println("π Account " + accountNumber + " has been deactivated");
}
}
public void activateAccount() {
if (!isActive) {
isActive = true;
System.out.println("π Account " + accountNumber + " has been activated");
}
}
// π― DISPLAY METHODS
public void displayAccountInfo() {
System.out.println("\n=== ACCOUNT INFORMATION ===");
System.out.println("Account Number: " + accountNumber);
System.out.println("Account Holder: " + accountHolder);
System.out.println("Account Type: " + accountType);
System.out.println("Balance: $" + balance);
System.out.println("Status: " + (isActive ? "Active" : "Inactive"));
}
public void displayMiniStatement() {
System.out.println("π Mini Statement for " + accountNumber);
System.out.println(" Holder: " + accountHolder);
System.out.println(" Balance: $" + balance);
System.out.println(" Status: " + (isActive ? "Active" : "Inactive"));
}
// π― PRIVATE HELPER METHOD
private String generateAccountNumber() {
return "ACC" + (1000 + totalAccounts);
}
// π― STATIC METHOD
public static int getTotalAccounts() {
return totalAccounts;
}
public static void displayBankInfo() {
System.out.println("\nπ¦ BANK INFORMATION");
System.out.println("Total Accounts: " + totalAccounts);
System.out.println("Bank Name: Java Trust Bank");
}
}
// π― MAIN BANKING SYSTEM
public class BankingSystem {
public static void main(String[] args) {
System.out.println("=== REAL-WORLD BANKING SYSTEM ===");
// π― CREATING BANK ACCOUNTS
System.out.println("\n1. ACCOUNT CREATION:");
BankAccount account1 = new BankAccount("Alice Johnson", "Savings", 1000.0);
BankAccount account2 = new BankAccount("Bob Smith", "Checking", 500.0);
BankAccount account3 = new BankAccount("Carol Davis", "Savings", 2000.0);
// π― ACCOUNT OPERATIONS
System.out.println("\n2. ACCOUNT OPERATIONS:");
account1.deposit(500.0);
account1.withdraw(200.0);
account2.deposit(1000.0);
account2.withdraw(800.0);
// π― TRANSFER BETWEEN ACCOUNTS
System.out.println("\n3. TRANSFER OPERATIONS:");
account1.transfer(account2, 300.0);
// π― ACCOUNT INFORMATION DISPLAY
System.out.println("\n4. ACCOUNT INFORMATION:");
account1.displayAccountInfo();
account2.displayAccountInfo();
account3.displayAccountInfo();
// π― ACCOUNT MANAGEMENT
System.out.println("\n5. ACCOUNT MANAGEMENT:");
account3.deactivateAccount();
account3.deposit(100.0); // Should fail
account3.activateAccount();
account3.deposit(100.0); // Should work
// π― MODIFYING ACCOUNT DETAILS
System.out.println("\n6. ACCOUNT MODIFICATIONS:");
account1.setAccountHolder("Alice Brown");
account1.displayMiniStatement();
// π― STATIC METHODS AND CLASS INFORMATION
System.out.println("\n7. BANK STATISTICS:");
BankAccount.displayBankInfo();
System.out.println("Total accounts created: " + BankAccount.getTotalAccounts());
// π― ARRAY OF ACCOUNTS
System.out.println("\n8. ACCOUNT COLLECTIONS:");
BankAccount[] accounts = {account1, account2, account3};
displayAllAccounts(accounts);
// π― SEARCH AND FILTER OPERATIONS
System.out.println("\n9. ACCOUNT SEARCH:");
findAccountByHolder(accounts, "Bob Smith");
findAccountsByType(accounts, "Savings");
}
// π― HELPER METHODS
public static void displayAllAccounts(BankAccount[] accounts) {
System.out.println("=== ALL ACCOUNTS ===");
double totalBalance = 0;
for (BankAccount account : accounts) {
account.displayMiniStatement();
totalBalance += account.getBalance();
}
System.out.println("Total Bank Balance: $" + totalBalance);
}
public static void findAccountByHolder(BankAccount[] accounts, String holderName) {
System.out.println("Searching for account holder: " + holderName);
for (BankAccount account : accounts) {
if (account.getAccountHolder().equalsIgnoreCase(holderName)) {
account.displayAccountInfo();
return;
}
}
System.out.println("No account found for: " + holderName);
}
public static void findAccountsByType(BankAccount[] accounts, String accountType) {
System.out.println("Accounts of type: " + accountType);
for (BankAccount account : accounts) {
if (account.getAccountType().equalsIgnoreCase(accountType)) {
account.displayMiniStatement();
}
}
}
}
Output:
=== REAL-WORLD BANKING SYSTEM === 1. ACCOUNT CREATION: β Account created: ACC1001 for Alice Johnson β Account created: ACC1002 for Bob Smith β Account created: ACC1003 for Carol Davis 2. ACCOUNT OPERATIONS: π° Deposited: $500.0 to ACC1001 New balance: $1500.0 πΈ Withdrawn: $200.0 from ACC1001 Remaining balance: $1300.0 π° Deposited: $1000.0 to ACC1002 New balance: $1500.0 πΈ Withdrawn: $800.0 from ACC1002 Remaining balance: $700.0 3. TRANSFER OPERATIONS: πΈ Withdrawn: $300.0 from ACC1001 Remaining balance: $1000.0 π° Deposited: $300.0 to ACC1002 New balance: $1000.0 π Transfer completed: $300.0 to ACC1002 4. ACCOUNT INFORMATION: === ACCOUNT INFORMATION === Account Number: ACC1001 Account Holder: Alice Johnson Account Type: Savings Balance: $1000.0 Status: Active === ACCOUNT INFORMATION === Account Number: ACC1002 Account Holder: Bob Smith Account Type: Checking Balance: $1000.0 Status: Active === ACCOUNT INFORMATION === Account Number: ACC1003 Account Holder: Carol Davis Account Type: Savings Balance: $2000.0 Status: Active 5. ACCOUNT MANAGEMENT: π Account ACC1003 has been deactivated β Deposit failed: Invalid amount or inactive account π Account ACC1003 has been activated π° Deposited: $100.0 to ACC1003 New balance: $2100.0 6. ACCOUNT MODIFICATIONS: βοΈ Account holder changed from 'Alice Johnson' to 'Alice Brown' π Mini Statement for ACC1001 Holder: Alice Brown Balance: $1000.0 Status: Active 7. BANK STATISTICS: π¦ BANK INFORMATION Total Accounts: 3 Bank Name: Java Trust Bank Total accounts created: 3 8. ACCOUNT COLLECTIONS: === ALL ACCOUNTS === π Mini Statement for ACC1001 Holder: Alice Brown Balance: $1000.0 Status: Active π Mini Statement for ACC1002 Holder: Bob Smith Balance: $1000.0 Status: Active π Mini Statement for ACC1003 Holder: Carol Davis Balance: $2100.0 Status: Active Total Bank Balance: $4100.0 9. ACCOUNT SEARCH: Searching for account holder: Bob Smith === ACCOUNT INFORMATION === Account Number: ACC1002 Account Holder: Bob Smith Account Type: Checking Balance: $1000.0 Status: Active Accounts of type: Savings π Mini Statement for ACC1001 Holder: Alice Brown Balance: $1000.0 Status: Active π Mini Statement for ACC1003 Holder: Carol Davis Balance: $2100.0 Status: Active
Example 4: Advanced OOP Concepts
// π― COMPLEX CLASS WITH COMPOSITION
class Address {
private String street;
private String city;
private String state;
private String zipCode;
public Address(String street, String city, String state, String zipCode) {
this.street = street;
this.city = city;
this.state = state;
this.zipCode = zipCode;
}
// Copy constructor
public Address(Address other) {
this.street = other.street;
this.city = other.city;
this.state = other.state;
this.zipCode = other.zipCode;
}
// Getters and setters
public String getFullAddress() {
return street + ", " + city + ", " + state + " " + zipCode;
}
public void displayAddress() {
System.out.println("Address: " + getFullAddress());
}
// ... other getters and setters
}
// π― MAIN CLASS WITH COMPOSITION
class Employee {
private String name;
private int employeeId;
private double salary;
private String department;
private Address address; // Composition - Employee HAS-A Address
private static int nextId = 1001;
// π― CONSTRUCTORS
public Employee(String name, double salary, String department, Address address) {
this.employeeId = nextId++;
this.name = name;
this.salary = salary;
this.department = department;
this.address = new Address(address); // Deep copy
}
public Employee(String name, double salary, String department,
String street, String city, String state, String zipCode) {
this(name, salary, department, new Address(street, city, state, zipCode));
}
// π― BUSINESS METHODS
public void giveRaise(double percentage) {
if (percentage > 0) {
double increase = salary * percentage / 100;
salary += increase;
System.out.println(name + " received a " + percentage + "% raise: +$" + increase);
}
}
public void transferDepartment(String newDepartment) {
String oldDept = this.department;
this.department = newDepartment;
System.out.println(name + " transferred from " + oldDept + " to " + newDepartment);
}
// π― GETTERS AND SETTERS
public String getName() { return name; }
public int getEmployeeId() { return employeeId; }
public double getSalary() { return salary; }
public String getDepartment() { return department; }
public Address getAddress() { return new Address(address); } // Return copy
public void setAddress(Address newAddress) {
this.address = new Address(newAddress); // Store copy
}
// π― DISPLAY METHODS
public void displayEmployeeInfo() {
System.out.println("\n=== EMPLOYEE INFORMATION ===");
System.out.println("ID: " + employeeId);
System.out.println("Name: " + name);
System.out.println("Department: " + department);
System.out.println("Salary: $" + salary);
address.displayAddress();
}
public void displayShortInfo() {
System.out.println(employeeId + " - " + name + " (" + department + ")");
}
}
// π― DEPARTMENT CLASS WITH AGGREGATION
class Department {
private String name;
private String manager;
private Employee[] employees;
private int employeeCount;
public Department(String name, String manager, int capacity) {
this.name = name;
this.manager = manager;
this.employees = new Employee[capacity];
this.employeeCount = 0;
}
// π― ADD EMPLOYEE TO DEPARTMENT
public boolean addEmployee(Employee employee) {
if (employeeCount < employees.length) {
employees[employeeCount++] = employee;
System.out.println("Added " + employee.getName() + " to " + name + " department");
return true;
}
System.out.println("Department " + name + " is full!");
return false;
}
// π― DEPARTMENT OPERATIONS
public void displayAllEmployees() {
System.out.println("\n=== " + name.toUpperCase() + " DEPARTMENT EMPLOYEES ===");
System.out.println("Manager: " + manager);
System.out.println("Total Employees: " + employeeCount);
double totalSalary = 0;
for (int i = 0; i < employeeCount; i++) {
employees[i].displayShortInfo();
totalSalary += employees[i].getSalary();
}
System.out.println("Total Department Salary: $" + totalSalary);
}
public Employee findEmployeeById(int id) {
for (int i = 0; i < employeeCount; i++) {
if (employees[i].getEmployeeId() == id) {
return employees[i];
}
}
return null;
}
public void giveDepartmentRaise(double percentage) {
System.out.println("\nGiving " + percentage + "% raise to all employees in " + name);
for (int i = 0; i < employeeCount; i++) {
employees[i].giveRaise(percentage);
}
}
}
// π― MAIN COMPANY SYSTEM
public class CompanySystem {
public static void main(String[] args) {
System.out.println("=== ADVANCED OOP: COMPANY MANAGEMENT SYSTEM ===");
// π― CREATING ADDRESSES
Address addr1 = new Address("123 Main St", "New York", "NY", "10001");
Address addr2 = new Address("456 Oak Ave", "Boston", "MA", "02101");
Address addr3 = new Address("789 Pine Rd", "Chicago", "IL", "60601");
// π― CREATING EMPLOYEES
Employee emp1 = new Employee("John Doe", 60000, "Engineering", addr1);
Employee emp2 = new Employee("Jane Smith", 55000, "Marketing", addr2);
Employee emp3 = new Employee("Mike Johnson", 70000, "Engineering", addr3);
Employee emp4 = new Employee("Sarah Wilson", 48000, "Sales",
"321 Elm St", "Seattle", "WA", "98101");
// π― CREATING DEPARTMENTS
Department engineering = new Department("Engineering", "Tech Director", 10);
Department marketing = new Department("Marketing", "Marketing Head", 8);
Department sales = new Department("Sales", "Sales Manager", 12);
// π― ADDING EMPLOYEES TO DEPARTMENTS
engineering.addEmployee(emp1);
engineering.addEmployee(emp3);
marketing.addEmployee(emp2);
sales.addEmployee(emp4);
// π― DISPLAY DEPARTMENT INFORMATION
engineering.displayAllEmployees();
marketing.displayAllEmployees();
sales.displayAllEmployees();
// π― EMPLOYEE OPERATIONS
System.out.println("\n=== EMPLOYEE OPERATIONS ===");
emp1.giveRaise(10);
emp2.transferDepartment("Product Management");
// Update address
Address newAddr = new Address("999 Innovation Dr", "San Francisco", "CA", "94102");
emp1.setAddress(newAddr);
// π― SEARCH AND DISPLAY
System.out.println("\n=== EMPLOYEE SEARCH ===");
Employee found = engineering.findEmployeeById(1001);
if (found != null) {
found.displayEmployeeInfo();
}
// π― DEPARTMENT-WIDE OPERATIONS
System.out.println("\n=== DEPARTMENT-WIDE OPERATIONS ===");
engineering.giveDepartmentRaise(5);
engineering.displayAllEmployees();
// π― DEMONSTRATING COMPOSITION
System.out.println("\n=== COMPOSITION DEMONSTRATION ===");
System.out.println("Employee HAS-A Address relationship:");
emp1.displayEmployeeInfo();
// π― DEMONSTRATING AGGREGATION
System.out.println("\n=== AGGREGATION DEMONSTRATION ===");
System.out.println("Department HAS-MANY Employees relationship:");
engineering.displayAllEmployees();
}
}
Output:
=== ADVANCED OOP: COMPANY MANAGEMENT SYSTEM === Added John Doe to Engineering department Added Mike Johnson to Engineering department Added Jane Smith to Marketing department Added Sarah Wilson to Sales department === ENGINEERING DEPARTMENT EMPLOYEES === Manager: Tech Director Total Employees: 2 1001 - John Doe (Engineering) 1002 - Mike Johnson (Engineering) Total Department Salary: $130000.0 === MARKETING DEPARTMENT EMPLOYEES === Manager: Marketing Head Total Employees: 1 1003 - Jane Smith (Marketing) Total Department Salary: $55000.0 === SALES DEPARTMENT EMPLOYEES === Manager: Sales Manager Total Employees: 1 1004 - Sarah Wilson (Sales) Total Department Salary: $48000.0 === EMPLOYEE OPERATIONS === John Doe received a 10% raise: +$6000.0 Jane Smith transferred from Marketing to Product Management === EMPLOYEE SEARCH === === EMPLOYEE INFORMATION === ID: 1001 Name: John Doe Department: Engineering Salary: $66000.0 Address: 999 Innovation Dr, San Francisco, CA 94102 === DEPARTMENT-WIDE OPERATIONS === Giving 5% raise to all employees in Engineering John Doe received a 5% raise: +$3300.0 Mike Johnson received a 5% raise: +$3500.0 === ENGINEERING DEPARTMENT EMPLOYEES === Manager: Tech Director Total Employees: 2 1001 - John Doe (Engineering) 1002 - Mike Johnson (Engineering) Total Department Salary: $138800.0 === COMPOSITION DEMONSTRATION === Employee HAS-A Address relationship: === EMPLOYEE INFORMATION === ID: 1001 Name: John Doe Department: Engineering Salary: $69300.0 Address: 999 Innovation Dr, San Francisco, CA 94102 === AGGREGATION DEMONSTRATION === Department HAS-MANY Employees relationship: === ENGINEERING DEPARTMENT EMPLOYEES === Manager: Tech Director Total Employees: 2 1001 - John Doe (Engineering) 1002 - Mike Johnson (Engineering) Total Department Salary: $138800.0
Key Concepts Summary
Class Components:
- Fields/Attributes: Variables that hold object state
- Constructors: Special methods to initialize objects
- Methods: Behaviors/functions objects can perform
- Access Modifiers: Control visibility (
public,private,protected) - Static Members: Belong to class, not objects
Object Creation Process:
- Declaration:
Car myCar; - Instantiation:
new Car() - Initialization: Constructor sets initial state
Memory Management:
- Stack: Stores primitive variables and object references
- Heap: Stores actual objects
- Garbage Collection: Automatically reclaims unused memory
Best Practices
- Use meaningful names for classes and methods
- Follow Java naming conventions (PascalCase for classes, camelCase for methods)
- Encapsulate fields (make them private, provide public getters/setters)
- Use constructors for proper object initialization
- Keep classes focused on a single responsibility
- Use composition over inheritance when possible
- Document your classes with JavaDoc comments
Common Patterns
JavaBean Pattern:
public class Person {
private String name;
private int age;
public Person() {}
public String getName() { return name; }
public void setName(String name) { this.name = name; }
// ... other getters/setters
}
Builder Pattern:
Person person = new Person.Builder()
.name("John")
.age(25)
.build();
Factory Pattern:
public class CarFactory {
public static Car createCar(String type) {
switch(type) {
case "sedan": return new Sedan();
case "suv": return new SUV();
default: throw new IllegalArgumentException();
}
}
}
Conclusion
Classes and objects are the building blocks of Java programming:
- β Classes define structure - like blueprints for houses
- β Objects are instances - the actual houses you can use
- β Encapsulation protects data - private fields with public methods
- β Constructors initialize objects - set up initial state
- β Methods define behavior - what objects can do
Key Takeaways:
- Every Java program needs at least one class
- Objects are created with
newkeyword - Constructors initialize object state
- Methods define object behavior
- Encapsulation is crucial for good OOP design
Remember: Mastering classes and objects is like learning to build with LEGO - once you understand the basic blocks, you can create amazing, complex structures! π§±ποΈ
Now you have a solid foundation to create robust, object-oriented Java applications!