Loading...

Sure! Here’s a Billing System that incorporates all the discussed concepts in Java, including classes, inheritance, polymorphism, exception handling, packages, generics, and file handling.

This example will simulate a billing system for a store, where we have different types of products, customer details, and billing processes.


Billing System Program

Directory Structure:

  • com.store.billing: Package for the billing system.
  • Classes: Product, Bill, Customer, BillingSystem, and Utility.

Step 1: Create the Product class

package com.store.billing;

public class Product {
    private String name;
    private double price;
    private int quantity;

    public Product(String name, double price, int quantity) {
        this.name = name;
        this.price = price;
        this.quantity = quantity;
    }

    public String getName() {
        return name;
    }

    public double getPrice() {
        return price;
    }

    public int getQuantity() {
        return quantity;
    }

    public double getTotalPrice() {
        return price * quantity;
    }
}

Step 2: Create the Customer class

package com.store.billing;

public class Customer {
    private String name;
    private String contact;
    private String address;

    public Customer(String name, String contact, String address) {
        this.name = name;
        this.contact = contact;
        this.address = address;
    }

    public String getName() {
        return name;
    }

    public String getContact() {
        return contact;
    }

    public String getAddress() {
        return address;
    }

    @Override
    public String toString() {
        return "Customer{name='" + name + "', contact='" + contact + "', address='" + address + "'}";
    }
}

Step 3: Create the Bill class (Using Generics)

package com.store.billing;

import java.util.List;

public class Bill<T extends Product> {
    private Customer customer;
    private List<T> products;
    private double totalAmount;

    public Bill(Customer customer, List<T> products) {
        this.customer = customer;
        this.products = products;
        calculateTotalAmount();
    }

    public Customer getCustomer() {
        return customer;
    }

    public List<T> getProducts() {
        return products;
    }

    public double getTotalAmount() {
        return totalAmount;
    }

    private void calculateTotalAmount() {
        totalAmount = 0;
        for (T product : products) {
            totalAmount += product.getTotalPrice();
        }
    }

    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("Bill Details:\n");
        sb.append("Customer: ").append(customer).append("\n");
        sb.append("Products: \n");
        for (T product : products) {
            sb.append(product.getName()).append(" - Quantity: ").append(product.getQuantity()).append(" - Total: ").append(product.getTotalPrice()).append("\n");
        }
        sb.append("Total Amount: ").append(totalAmount).append("\n");
        return sb.toString();
    }
}

Step 4: Create the BillingSystem class

package com.store.billing;

import java.io.*;
import java.util.*;

public class BillingSystem {
    private List<Bill<?>> bills = new ArrayList<>();

    public void addBill(Bill<?> bill) {
        bills.add(bill);
    }

    public void printAllBills() {
        for (Bill<?> bill : bills) {
            System.out.println(bill);
        }
    }

    public void saveBillsToFile(String filename) throws IOException {
        try (BufferedWriter writer = new BufferedWriter(new FileWriter(filename))) {
            for (Bill<?> bill : bills) {
                writer.write(bill.toString());
                writer.write("\n\n");
            }
        }
    }

    public void readBillsFromFile(String filename) throws IOException {
        try (BufferedReader reader = new BufferedReader(new FileReader(filename))) {
            String line;
            while ((line = reader.readLine()) != null) {
                System.out.println(line);
            }
        }
    }
}

Step 5: Create the Utility class (For Exception Handling)

package com.store.billing;

public class Utility {
    public static void validateInput(String input) throws IllegalArgumentException {
        if (input == null || input.isEmpty()) {
            throw new IllegalArgumentException("Input cannot be empty or null.");
        }
    }

    public static void validatePrice(double price) throws IllegalArgumentException {
        if (price < 0) {
            throw new IllegalArgumentException("Price cannot be negative.");
        }
    }

    public static void validateQuantity(int quantity) throws IllegalArgumentException {
        if (quantity <= 0) {
            throw new IllegalArgumentException("Quantity must be greater than zero.");
        }
    }
}

Step 6: Create the Main class to run the program

package com.store.billing;

import java.io.IOException;
import java.util.*;

public class Main {
    public static void main(String[] args) {
        try {
            // Creating products
            Product apple = new Product("Apple", 1.2, 10);
            Product banana = new Product("Banana", 0.8, 20);
            Product orange = new Product("Orange", 1.5, 5);

            // Creating a customer
            Customer customer = new Customer("John Doe", "1234567890", "123 Main St");

            // Creating a bill for the customer
            List<Product> productList = new ArrayList<>();
            productList.add(apple);
            productList.add(banana);
            productList.add(orange);

            Bill<Product> bill = new Bill<>(customer, productList);

            // Creating a billing system and adding the bill
            BillingSystem billingSystem = new BillingSystem();
            billingSystem.addBill(bill);

            // Printing all bills
            billingSystem.printAllBills();

            // Saving bills to a file
            billingSystem.saveBillsToFile("bills.txt");

            // Reading bills from the file
            System.out.println("\nReading from file:");
            billingSystem.readBillsFromFile("bills.txt");

        } catch (IllegalArgumentException e) {
            System.out.println("Error: " + e.getMessage());
        } catch (IOException e) {
            System.out.println("Error while handling file: " + e.getMessage());
        }
    }
}

Explanation of the Program

  1. Product Class: Represents individual products in the store with properties like name, price, and quantity. It includes a method to calculate the total price of the product based on its quantity.
  2. Customer Class: Represents a customer with basic details like name, contact, and address.
  3. Bill Class: Contains information about a customer’s bill, including the customer’s details and the products they bought. The class also includes a method to calculate the total amount for the bill.
  4. BillingSystem Class: Manages multiple bills. It allows adding new bills, printing all bills, and saving or reading bills from a file. It also uses exception handling for file operations.
  5. Utility Class: Provides helper methods for input validation, ensuring that invalid data (e.g., negative price, zero quantity) is handled correctly.
  6. Main Class: Simulates a store’s billing system by creating products, customers, and bills, and interacts with the billing system. It also handles exceptions gracefully using try-catch.

Key Features of the Program

  • Inheritance: Although not heavily used in this example, you could extend the Product class into different product types (e.g., Electronics, Groceries).
  • Polymorphism: The Bill class uses generics to handle different types of products, demonstrating polymorphism.
  • Generics: The Bill class is designed to be generic, so it can handle any type of Product or its subclasses.
  • Exception Handling: The Utility class handles invalid inputs, and the main program catches exceptions related to file handling and input validation.
  • File Handling: Bills are saved and read from a text file using BufferedWriter and BufferedReader.

This program integrates all the concepts discussed so far in Java to build a functional and organized billing system! Let me know if you’d like to add more features or modify it further. 😊