0% found this document useful (0 votes)
4 views30 pages

Hexaware Week 2 Notes (Java)

The document outlines the design of a retail store system similar to DMart, focusing on key programming concepts such as classes, objects, encapsulation, inheritance, polymorphism, interfaces, and abstract classes. It details the core features of the system, including product management, customer interactions, billing, and payment processing, along with code examples illustrating these concepts. The importance of constructors, packages, and access modifiers in ensuring code organization, security, and maintainability is also emphasized.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views30 pages

Hexaware Week 2 Notes (Java)

The document outlines the design of a retail store system similar to DMart, focusing on key programming concepts such as classes, objects, encapsulation, inheritance, polymorphism, interfaces, and abstract classes. It details the core features of the system, including product management, customer interactions, billing, and payment processing, along with code examples illustrating these concepts. The importance of constructors, packages, and access modifiers in ensuring code organization, security, and maintainability is also emphasized.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Mepco Schlenk Engineering College (Autonomous), Sivakasi

Hexaware (JAVA -Week 2 Material)

Let’s explore the following concepts in the context of a DMart system design
1. Classes, Objects, Encapsulation
2. Inheritance, Polymorphism
3. Interfaces & Abstract Classes
4. Constructor Usage
5. Packages & Access Modifiers
6. String & Utility Classes
7. Object Relationships & Composition

Imagine you’re designing a retail store system like a mini version of


DMart:
Core Features
 Manage products (rice, soap, TV, etc.)
 Customers add items to cart
 Generate bill
 Apply discounts/taxes
 Handle payments (UPI, card, cash)
 Update inventory
Key Entities (Your Classes)
These are the main building blocks:
 Product → name, price, stock
 Customer → name, contact
 Cart → list of selected products
 Order → finalized purchase
 Payment → how user pays
 Inventory → stock management
 Billing → price calculation
System Flow (End-to-End)
1. Customer enters store
2. Adds products to cart
3. System checks inventory
4. Order is created
5. Bill is generated
6. Payment is processed
7. Inventory is updated

1. Classes, Objects, Encapsulation


Class
A class is a blueprint/template used to create objects. It defines:
 properties (variables)
 behaviors (methods)
Object
An object is an instance of a class that represents a real-world entity.
Encapsulation
Encapsulation is the process of wrapping data (variables) and methods
together and restricting direct access to data

In DMart System:
 Class → defines entities like Product, Customer
 Object → actual product like “Rice bag”, “Soap”
 Encapsulation → protects:
o stock (should not go negative)
o price (should not be arbitrarily changed)
Code (DMart Example)
class Product {
// Encapsulated data (private)
private String name;
private double price;
private int stock;

// Constructor
public Product(String name, double price, int stock) {
[Link] = name;
[Link] = price;
[Link] = stock;
}

// Getter methods
public String getName() {
return name;
}

public double getPrice() {


return price;
}

public int getStock() {


return stock;
}

// Setter with validation (Encapsulation logic)


public void setStock(int stock) {
if (stock >= 0) {
[Link] = stock;
} else {
[Link]("Stock cannot be negative!");
}
}

// Business method
public void displayProduct() {
[Link]("Product: " + name + ", Price: " + price + ", Stock: "
+ stock);
}
}
Main Method
public class Main {
public static void main(String[] args) {

// Object creation
Product p1 = new Product("Rice", 50.0, 100);

[Link]();

// Valid update
[Link](80);

// Invalid update
[Link](-10);

[Link]();
}
}
Output
Product: Rice, Price: 50.0, Stock: 100
Stock cannot be negative!
Product: Rice, Price: 50.0, Stock: 80
Explanation
Class → Product
Defines structure:
 name
 price
 stock
Object → p1
Represents a real product in store:
 Rice, ₹50, 100 units
Encapsulation Flow
Without encapsulation:
[Link] = -10; // ❌ dangerous
With encapsulation:
[Link](-10); // ✅ controlled
We control how data is modified

Real-world Mapping
 Inventory system must never allow:
o negative stock
o unauthorized price change
Encapsulation ensures this.

Common Interview Traps


“Encapsulation = data hiding”
✔️Correct: Data hiding is part of encapsulation

Making everything public


public int stock; // ❌ bad practice

Only getters/setters = encapsulation


✔️Real encapsulation = business logic + validation
2. Inheritance & Polymorphism
Inheritance
Inheritance is a mechanism where one class (child) acquires properties
and behavior of another class (parent). Represents IS-A relationship

Polymorphism
Polymorphism means one method behaves differently based on the
object
Types:
 Compile-time → Method Overloading
 Runtime → Method Overriding ⭐ (important)

In DMart System:
We have different product types:
 Grocery → discount applied
 Electronics → tax applied
Instead of writing separate logic everywhere: Use inheritance +
polymorphism

Importance of Inheritance & Polymorphism:


 Code reuse
 Scalability
 Cleaner design
 Easy to extend (add new product types)
Code (DMart Example)
Base Class (Parent)
class Product {
protected String name;
protected double price;

public Product(String name, double price) {


[Link] = name;
[Link] = price;
}

// Method to be overridden
public double calculatePrice() {
return price;
}
public void display() {
[Link](name + " Final Price: " + calculatePrice());
}
}

Child Class 1 (Grocery)


class Grocery extends Product {

public Grocery(String name, double price) {


super(name, price);
}

@Override
public double calculatePrice() {
return price * 0.9; // 10% discount
}
}

Child Class 2 (Electronics)


class Electronics extends Product {

public Electronics(String name, double price) {


super(name, price);
}

@Override
public double calculatePrice() {
return price * 1.18; // 18% tax
}
}
Main Method
public class Main {
public static void main(String[] args) {

Product p1 = new Grocery("Rice", 100);


Product p2 = new Electronics("TV", 10000);

[Link]();
[Link]();
}
}
Output
Rice Final Price: 90.0
TV Final Price: 11800.0
Explanation (Deep Understanding)
Inheritance Flow
Product (Parent)

├── Grocery
└── Electronics
Grocery IS-A Product
Electronics IS-A Product
Polymorphism (Key Point 🔥)
Product p1 = new Grocery("Rice", 100);
Reference type = Product
Object type = Grocery
At runtime:
[Link]();
Calls Grocery version, not Product
This is Runtime Polymorphism (Dynamic Method Dispatch)

Why This is Powerful


You can write:
List<Product> items;
And store:
 Grocery
 Electronics
 Any future product
System becomes extensible
Common Interview Traps
1: Overloading vs Overriding
Feature Overloadi Overridi
ng ng
Same method ✅ ✅
name
Same parameters ❌ ✅
Runtime ❌ ✅
polymorphism
2: Static methods
static void method() {}
Cannot be overridden (only hidden)
3: Access level
Child cannot reduce visibility:
public → protected ❌
4: Final methods
final void method() {}
Cannot override
3. Interfaces & Abstract Classes
Interface
An interface is a contract that defines what a class must do, but not how it
does it
 Contains abstract methods (by default)
 A class implements an interface
Abstract Class
An abstract class is a class that cannot be instantiated and can have both
abstract + concrete methods
 Used for partial implementation
 A class extends an abstract class

In DMart System:
We need flexibility in:
 Payment methods → UPI, Card, Cash
 User roles → Customer, Admin
Importance of Interfaces & Abstract Classes:
 Loose coupling
 Scalability
 Clean architecture
 Easy to add new features without breaking code

Code (DMart Example)


1:Interface (Payment System)
Interface
interface Payment {
void pay(double amount);
}
Implementations
class UpiPayment implements Payment {
public void pay(double amount) {
[Link]("Paid " + amount + " using UPI");
}
}
class CardPayment implements Payment {
public void pay(double amount) {
[Link]("Paid " + amount + " using Card");
}
}
Usage
public class Main {
public static void main(String[] args) {

Payment payment;

payment = new UpiPayment();


[Link](500);

payment = new CardPayment();


[Link](1000);
}
}
Output
Paid 500.0 using UPI
Paid 1000.0 using Card
Explanation (Interface)
 Payment defines a rule: all payment types must implement pay()
 Each class gives its own implementation
 At runtime → correct method is called (polymorphism)

2: Abstract Class (User System)


Abstract Class
abstract class User {
protected String name;

public User(String name) {


[Link] = name;
}

// Abstract method
abstract void getRole();

// Concrete method
public void displayName() {
[Link]("User: " + name);
}
}
Child Classes
class Customer extends User {
public Customer(String name) {
super(name);
}

void getRole() {
[Link]("Role: Customer");
}
}
class Admin extends User {

public Admin(String name) {


super(name);
}

void getRole() {
[Link]("Role: Admin");
}
}
Usage
public class Main {
public static void main(String[] args) {

User u1 = new Customer("Rahul");


User u2 = new Admin("Manager");

[Link]();
[Link]();

[Link]();
[Link]();
}
}
Output
User: Rahul
Role: Customer
User: Manager
Role: Admin

Interface Flow (Payment)


Payment (interface)

├── UpiPayment
└── CardPayment
You can easily add:
class CashPayment implements Payment
✔️No change in existing code → Open/Closed Principle

Abstract Class Flow (User)


User (abstract)

├── Customer
└── Admin
Common logic:
 name
 displayName()
Different behavior:
 roles
Interface vs Abstract Class (IMPORTANT)
Feature Interface Abstract Class
Keyword implements extends
Multiple ✅ ❌
inheritance
Methods abstract + abstract +
default concrete
Constructors ❌ ✅
Fields constants only any

Common Interview Traps


“Interface cannot have methods with body”
✔️Since Java 8 → can have default & static

“Abstract class = interface”


✔️No—abstract class can have state & constructors

Multiple inheritance confusion


✔️Java allows: class A implements X, Y

Interface vs Abstract class?


Interface defines a contract for behavior, while an abstract class provides
partial implementation.
In a retail system, interfaces are used for flexible components like payment
methods, while abstract classes are used for shared base entities like users.
4. Constructor Usage
A constructor is a special method used to initialize objects when they are
created
Key Properties:
 Same name as class
 No return type
 Called automatically when object is created
In DMart System:
 Ensure every object is created with valid data
 Avoid incomplete objects like:
o Product without price ❌
o Order without items ❌
Importance of Constructor:
 Object consistency ✅
 Safer code (no null states)
 Used in dependency injection (very important)
Code (DMart Example)
Product with Constructor
class Product {
private String name;
private double price;
private int stock;

// Parameterized Constructor
public Product(String name, double price, int stock) {
[Link] = name;
[Link] = price;
[Link] = stock;
}

public void display() {


[Link](name + " - Price: " + price + ", Stock: " + stock);
}
}
Order Class
import [Link];

class Order {
private int orderId;
private List<Product> products;
// Constructor ensures order always has data
public Order(int orderId, List<Product> products) {
[Link] = orderId;
[Link] = products;
}

public void displayOrder() {


[Link]("Order ID: " + orderId);
for (Product p : products) {
[Link]();
}
}
}
Main Method
import [Link];

public class Main {


public static void main(String[] args) {

Product p1 = new Product("Rice", 50, 100);


Product p2 = new Product("Soap", 30, 200);

Order order = new Order(101, [Link](p1, p2));

[Link]();
}
}
Output
Order ID: 101
Rice - Price: 50.0, Stock: 100
Soap - Price: 30.0, Stock: 200
Explanation
Object Creation Flow
Product p1 = new Product("Rice", 50, 100);
Steps:
1. Memory allocated
2. Constructor called
3. Values initialized
Why Constructor is Important
Without constructor:
Product p = new Product();
[Link] = "Rice"; // ❌ unsafe (if public)
Object may be:
 incomplete
 inconsistent

Constructor Ensures Valid State


public Product(String name, double price, int stock)
Every product must have:
 name
 price
 stock
✔️No invalid object creation

Real System Insight (VERY IMPORTANT)


Dependency Injection Concept
class BillingService {
private Payment payment;

public BillingService(Payment payment) {


[Link] = payment;
}
}
Inject dependency via constructor
✔️Used in Spring Boot / real systems

Types of Constructors
Default Constructor
Product() {
[Link]("Default constructor");
}
Provided by compiler if none exists

Parameterized Constructor (MOST USED)


Product(String name, double price)
Constructor Chaining
this(); // same class
super(); // parent class
Common Interview Traps
1: Constructor vs Method
void Product() {} // ❌ NOT constructor
2: Default constructor missing
If you define:
Product(String name)
Compiler will NOT create default constructor
3: Can constructor be overridden?
NO
Because constructors are not inherited
4: Can constructor be private?
YES (used in Singleton pattern)

What is a constructor?
A constructor is used to initialize objects at the time of creation.
In systems like retail, it ensures objects like Product or Order are always
created with valid data, preventing inconsistent states.
5. Packages & Access Modifiers
A package is a namespace that groups related classes and interfaces
together
Think of it like folders in a project
Access Modifiers
Access modifiers define who can access a class, variable, or method
Types:
 private
 default (no keyword)
 protected
 public
In DMart System:
We will organize code like a real company:
[Link]
├── model → Product, Order
├── service → BillingService, PaymentService
├── repository → Inventory
└── controller → Main / API
Importance of Package:
 Clean architecture
 Code maintainability
 Security (restrict access properly)
 Avoid naming conflicts
3. Code (DMart Example)
Package Declaration
package [Link];
Product Class (Model Layer)
package [Link];

public class Product {


private String name; // only inside class
private double price;
protected int stock; // accessible in subclass

public Product(String name, double price, int stock) {


[Link] = name;
[Link] = price;
[Link] = stock;
}
public String getName() {
return name;
}

protected void updateStock(int value) {


[Link] = value;
}
}
Billing Service (Different Package)
package [Link];

import [Link];

public class BillingService {

public void printProduct(Product p) {


[Link]([Link]());

// [Link]([Link]); ❌ not accessible


}
}
Main Class
package [Link];

import [Link];
import [Link];

public class Main {


public static void main(String[] args) {

Product p = new Product("Rice", 50, 100);

BillingService service = new BillingService();


[Link](p);
}
}

Output
Rice
Explanation

Package Flow
[Link] → Product
[Link] → BillingService
[Link] → Main
Separation of concerns:
 Model → data
 Service → logic

Access Modifier Behavior


private
private double price;
✔️Accessible only inside class
❌ Not accessible outside
👉 Protects sensitive data (price, stock)

default (no keyword)


✔️Accessible within same package
❌ Not outside package

protected
✔️Same package
✔️Subclasses (even in different packages)

public
✔️Accessible everywhere

Summary Table
Modifie Same Same Subcla Outsi
r Class Package ss de
private ✅ ❌ ❌ ❌
default ✅ ✅ ❌ ❌
protecte ✅ ✅ ✅ ❌
d
public ✅ ✅ ✅ ✅
Real DMart Mapping
Field Modifie Reason
r
price private prevent direct
change
stock protecte allow subclass
d control
metho public allow system
ds access

Common Interview Traps


1: protected misunderstanding
Many think:
 protected = same package only ❌
✔️Correct:
 same package + subclass access
2: default keyword confusion
int x; // default
✔️No keyword = default
3: public everything
public double price; // ❌ bad practice
Breaks encapsulation
4: package not used
In interviews:
 flat structure = ❌
 layered structure = ✅

What are access modifiers?


Access modifiers control visibility of classes and members. In real systems
like retail applications, they are used to protect sensitive data like price and
enforce proper architecture using packages.
6. String & Utility Classes
String
A String in Java is an object that represents a sequence of characters
Most important property: Strings are immutable (cannot be changed
once created)

Utility Classes
Utility classes are helper classes that provide reusable methods for common
tasks
Examples:
 StringBuilder
 StringBuffer
 Math
 Arrays

In DMart System:
We use Strings for:
 Bill generation
 Product names
 Invoice formatting
 Logging

Importance:
 Performance optimization
 Memory efficiency
 Thread safety (StringBuffer)
 Avoid unnecessary object creation
Code (DMart Example)
Problem with String (Immutable)
public class Main {
public static void main(String[] args) {

String bill = "Items: ";

[Link]("Rice ");
[Link]("Soap ");

[Link](bill);
}
}
Output
Items:

Explanation
👉 Strings are immutable
👉 Every concat creates a new object
👉 Original string NOT changed
Correct Approach: StringBuilder

Using StringBuilder (Best for Billing System)


public class Main {
public static void main(String[] args) {

StringBuilder bill = new StringBuilder();

[Link]("Items: ");
[Link]("Rice ");
[Link]("Soap ");

[Link]([Link]());
}
}
Output
Items: Rice Soap

StringBuffer (Thread-safe version)


public class Main {
public static void main(String[] args) {

StringBuffer bill = new StringBuffer();

[Link]("Items: ");
[Link]("Milk ");
[Link]("Bread ");

[Link]([Link]());
}
}
Output
Items: Milk Bread
Why String is Immutable?
In DMart system:
 Bill should not change accidentally
 Security (price/invoice integrity)
 Safe for caching

String Pool Concept


String s1 = "DMart";
String s2 = "DMart";
Both point to same memory in String Pool
✔️Saves memory
✔️Improves performance

StringBuilder vs StringBuffer
Feature StringBuil StringBu
der ffer
Thread- ❌ ✅
safe
Performan Fast ⚡ Slow
ce
Use case Single Multi-
thread thread

Real DMart Mapping


Use Case Class
Bill generation StringBuild
er
Invoice storage String
Multi-user billing StringBuff
system er
Product name String

Utility Classes (Real Usage)


Math Utility
public class Main {
public static void main(String[] args) {

double price = 99.99;


[Link]([Link](price));
}
}
Output
100
Arrays Utility
import [Link];

public class Main {


public static void main(String[] args) {

int[] arr = {5, 2, 8, 1};

[Link](arr);

[Link]([Link](arr));
}
}
Output
[1, 2, 5, 8]
Common Interview Traps
1: String modification assumption
[Link]("x"); // ❌ does not change original string
2: Using String in loops
Bad practice:
String s = "";
for(int i=0;i<1000;i++){
s += i;
}
✔️Should use StringBuilder
3: Confusing StringBuffer & Builder
 Buffer = thread-safe
 Builder = faster
4: Ignoring memory impact
String misuse = performance bottleneck in large systems
Why is String immutable?
String is immutable to ensure security, thread safety, and efficient memory
management using the string pool. In systems like billing, it prevents
accidental modification of critical data like invoices.
7. Object Relationships & Composition
Object Relationships
Object relationships describe how classes are connected in a system.
Types:
 Association
 Aggregation
 Composition

Composition (MOST IMPORTANT)


Composition means one object owns another object completely
If parent dies → child also dies

In DMart System:
We model real-world structure:
 Store has Products
 Cart has Products
 Order has Cart
 Billing depends on Order

Importance :
 Represents real-world systems accurately
 Helps design scalable architecture
 Reduces tight coupling
 Core concept in Low-Level Design (LLD)

Code (DMart Example)


1. Association (Basic Relationship)
class Customer {
String name;

Customer(String name) {
[Link] = name;
}
}
class Store {
Customer customer; // association

Store(Customer customer) {
[Link] = customer;
}
}

Aggregation (HAS-A, weak ownership)


Products exist even if Store is removed
import [Link];

class Store {
List<Product> products;

Store(List<Product> products) {
[Link] = products;
}
}

Composition (STRONG ownership)


Core DMart concept

Product Class
class Product {
String name;

Product(String name) {
[Link] = name;
}

void show() {
[Link](name);
}
}

Cart (COMPOSITION)
import [Link];

class Cart {
private List<Product> products;

Cart(List<Product> products) {
[Link] = products;
}
void showCart() {
for (Product p : products) {
[Link]();
}
}
}

Main Class
import [Link];

public class Main {


public static void main(String[] args) {

Product p1 = new Product("Rice");


Product p2 = new Product("Soap");

Cart cart = new Cart([Link](p1, p2));

[Link]();
}
}

Output
Rice
Soap

Explanation
Association
Customer ↔ Store
👉 Loose connection
👉 Both can exist independently
Example:
 Customer exists without store
 Store exists without customer
Aggregation (HAS-A weak relationship)
Store → Products
👉 Products can exist independently
👉 Store only "uses" them
Composition (STRONG HAS-A)
Cart → Products
👉 If Cart is deleted:
 Products in that cart are also gone (logically)
👉 This is used in:
 Cart system
 Order system
 Billing system

Real DMart Mapping


Relations Example
hip
Association Customer ↔ Store
Aggregatio Store → Inventory
n Products
Compositio Cart → Products
n
Compositio Order → Cart Items
n

Common Interview Traps


1: Confusing Aggregation vs Composition
Type Owners
hip
Aggregatio Weak
n
Compositi Strong
on

2: Thinking composition = inheritance


Wrong ❌
Composition = HAS-A
Inheritance = IS-A

3: Overusing inheritance
Real systems prefer:
 Composition over inheritance

4: Not modeling real-world correctly


Example mistake:
 Making Cart extend Product ❌
✔️Correct:
 Cart HAS Products ✔️

What is composition?
Composition is a strong relationship where one object owns another object. If
the parent object is destroyed, the child object also gets destroyed. In retail
systems like DMart, a cart contains products, making it a composition
relationship.

You might also like