Careeroza
Real World Example
Shopping Cart
Every e-commerce app (Flipkart, Amazon, Nykaa) has a cart. In Java it is naturally modelled with classes: a CartItem holds a product and quantity, and a Cart holds the items and calculates totals.
Example
public class Main {
public static void main(String[] args) {
Cart cart = new Cart("Neha");
cart.add(new CartItem("Running Shoes", 2499, 1));
cart.add(new CartItem("Sports Socks", 199, 3));
cart.add(new CartItem("Water Bottle", 349, 2));
cart.printSummary();
}
}
class CartItem {
String name;
double price;
int qty;
CartItem(String name, double price, int qty) {
this.name = name;
this.price = price;
this.qty = qty;
}
double lineTotal() {
return price * qty;
}
}
class Cart {
String owner;
CartItem[] items = new CartItem[10];
int size = 0;
Cart(String owner) {
this.owner = owner;
}
void add(CartItem item) {
items[size++] = item;
}
double total() {
double sum = 0;
for (int i = 0; i < size; i++) sum += items[i].lineTotal();
return sum;
}
void printSummary() {
System.out.println(owner + "'s cart");
for (int i = 0; i < size; i++) {
CartItem it = items[i];
System.out.printf(" %-14s %d x %7.2f = %8.2f%n", it.name, it.qty, it.price, it.lineTotal());
}
double total = total();
double delivery = total >= 999 ? 0 : 49;
System.out.printf(" Items total: %.2f, Delivery: %.2f, Pay: %.2f%n", total, delivery, total + delivery);
}
}Output
Neha's cart Running Shoes 1 x 2499.00 = 2499.00 Sports Socks 3 x 199.00 = 597.00 Water Bottle 2 x 349.00 = 698.00 Items total: 3794.00, Delivery: 0.00, Pay: 3794.00
What Comes Next
You now know the building blocks of Java: variables, types, operators, strings, conditions, loops, arrays, methods, input and a first look at classes. The medium level goes deeper into OOP (encapsulation, inheritance, polymorphism, interfaces), exceptions, collections, generics and more.