Introduction to Object-Oriented Programming in Java: A Practical Guide
Object-Oriented Programming (OOP) is a powerful paradigm that allows developers to model real-world entities using classes and objects. In this blog, I’ll walk you through a set of Java programs I developed as part of an assignment to demonstrate key OOP concepts like encapsulation, inheritance, and polymorphism. The solutions address four tasks: creating a Person class, managing Product data, handling an Account system, and implementing inheritance with Person and Employee classes. All code is available in my GitHub repository.
Task 1: Person Class
Problem Statement
Create a Person class with name and age properties, featuring:
Default age of 18.
A constructor to initialize name and age.
A method to display the person’s details.
Solution
public class Person {
private String name;
private int age;
// Default constructor
public Person() {
this.age = 18;
}
// Parameterized constructor
public Person(String name, int age) {
this.name = name;
this.age = age;
}
// Display method
public void display() {
System.out.println("Name: " + name + ", Age: " + age);
}
}
OOP Concepts Used
Encapsulation: The name and age fields are private, ensuring data is accessed only through constructors or methods, protecting the object’s state.
Constructor Overloading: Two constructors (default and parameterized) allow flexibility in object creation.
Explanation
The Person class demonstrates basic OOP principles. The default constructor sets age to 18, while the parameterized constructor allows custom initialization. The display method outputs the person’s details. I tested it by creating two objects: one with default values and one with custom values.
Task 2: Product and ProductMain Classes
Problem Statement
Create a Product class with pid, price, and quantity, and a ProductMain class to:
Accept details for 5 products and store them in an array.
Find the pid of the product with the highest price.
Calculate the total amount spent (price * quantity) for all products.
Solution
// Product.java
public class Product {
private int pid;
private double price;
private int quantity;
public Product(int pid, double price, int quantity) {
this.pid = pid;
this.price = price;
this.quantity = quantity;
}
public int getPid() { return pid; }
public double getPrice() { return price; }
public int getQuantity() { return quantity; }
}
// ProductMain.java
import java.util.Scanner;
public class ProductMain {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
Product[] products = new Product[5];
// Accept product details
for (int i = 0; i < 5; i++) {
System.out.println("Enter details for Product " + (i + 1) + ":");
System.out.print("PID: ");
int pid = scanner.nextInt();
System.out.print("Price: ");
double price = scanner.nextDouble();
System.out.print("Quantity: ");
int quantity = scanner.nextInt();
products[i] = new Product(pid, price, quantity);
}
// Find product with highest price
int maxPid = products[0].getPid();
double maxPrice = products[0].getPrice();
for (int i = 1; i < products.length; i++) {
if (products[i].getPrice() > maxPrice) {
maxPrice = products[i].getPrice();
maxPid = products[i].getPid();
}
}
System.out.println("PID of product with highest price: " + maxPid);
// Calculate total amount
double totalAmount = calculateTotalAmount(products);
System.out.println("Total amount spent: " + totalAmount);
scanner.close();
}
public static double calculateTotalAmount(Product[] products) {
double total = 0;
for (Product p : products) {
total += p.getPrice() * p.getQuantity();
}
return total;
}
}
OOP Concepts Used
Encapsulation: The Product class uses private fields with public getters to control access.
Modularity: The calculateTotalAmount method is a static utility function in ProductMain, promoting code reuse.
Array of Objects: The program manages multiple Product objects in an array, showcasing object-oriented data handling.
Explanation
The Product class encapsulates product details, and ProductMain handles user input and logic. The program prompts for 5 products, stores them in an array, identifies the product with the highest price, and computes the total amount spent. The use of getters ensures safe data access.
Task 3: Account Class
Problem Statement
Create an Account class with a balance field, featuring:
Two constructors (no-arg and parameterized).
Methods to deposit, withdraw, and display the balance.
Solution
public class Account {
private double balance;
public Account() {
this.balance = 0.0;
}
public Account(double balance) {
this.balance = balance;
}
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 balance");
}
}
public void displayBalance() {
System.out.println("Current Balance: " + balance);
}
}
OOP Concepts Used
Encapsulation: The balance is private, and methods control modifications.
Input Validation: The deposit and withdraw methods include checks to ensure valid transactions.
Constructor Overloading: Provides flexibility in initializing accounts.
Explanation
The Account class models a bank account. The no-arg constructor initializes balance to 0, while the parameterized constructor sets a custom balance. The deposit and withdraw methods include validation to prevent negative or invalid transactions. The displayBalance method shows the current balance. I tested it with various scenarios, including invalid withdrawals.
Task 4: Person and Employee Classes (Inheritance)
Problem Statement
Create a Person base class with name and age, and an Employee subclass that adds employeeID and salary. Use the super keyword to initialize Person attributes.
Solution
// Person.java
public class Person {
protected String name;
protected int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public void display() {
System.out.println("Name: " + name + ", Age: " + age);
}
}
// Employee.java
public class Employee extends Person {
private String employeeID;
private double salary;
public Employee(String name, int age, String employeeID, double salary) {
super(name, age);
this.employeeID = employeeID;
this.salary = salary;
}
public void display() {
super.display();
System.out.println("Employee ID: " + employeeID + ", Salary: " + salary);
}
}
OOP Concepts Used
Inheritance: Employee extends Person, inheriting its fields and methods.
Polymorphism: The display method in Employee overrides Person’s method, extending its functionality.
Super Keyword: Used to call the Person constructor and method, ensuring proper initialization and reuse.
Explanation
The Person class serves as a base with name and age. The Employee class inherits from Person, adding employeeID and salary. The super keyword initializes the inherited fields, and the overridden display method calls the parent’s version before adding employee-specific details. This demonstrates inheritance and method overriding effectively.
Key Takeaways
This assignment reinforced my understanding of OOP in Java:
Encapsulation protects data and ensures controlled access.
Inheritance promotes code reuse and hierarchical modeling.
Polymorphism allows flexible method implementations.
Constructor Overloading enhances object initialization options.
Top comments (0)