0% found this document useful (0 votes)
10 views

5JAVA.docx

The document outlines the development of a Java program using abstract classes and interfaces to demonstrate key Object-Oriented Programming concepts such as abstraction and polymorphism. It includes examples of an online shopping cart system, a vehicle abstraction example, and an online payment system, each illustrating the use of abstract classes and methods. Additionally, it discusses the importance of interfaces in achieving abstraction, multiple inheritance, and loose coupling in Java.

Uploaded by

knb.23.09.2008
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views

5JAVA.docx

The document outlines the development of a Java program using abstract classes and interfaces to demonstrate key Object-Oriented Programming concepts such as abstraction and polymorphism. It includes examples of an online shopping cart system, a vehicle abstraction example, and an online payment system, each illustrating the use of abstract classes and methods. Additionally, it discusses the importance of interfaces in achieving abstraction, multiple inheritance, and loose coupling in Java.

Uploaded by

knb.23.09.2008
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 27

Aim : Develop a program using an abstract class and an interface with Java features

like default and static methods. Show polymorphism with overriding methods.

Theory :

●​ Abstraction is one of the key concepts in Object-Oriented Programming


(OOP). It refers to the hiding of implementation details and showing only
the essential features of an object.
●​ In Java, abstraction is achieved through abstract classes or interfaces.
While an abstract class can have both abstract (unimplemented) and
concrete (implemented) methods, an interface in Java is a purely abstract
type that defines a contract or blueprint for classes without providing any
implementation.
●​ In interfaces, all methods are implicitly abstract (prior to Java 8). You can
also define default methods with implementation and static methods in
interfaces starting from Java 8. Interfaces are typically used to achieve
multiple inheritance, which is not allowed with classes.
●​ Abstraction is a process of hiding the implementation details from the
user, only the functionality will be provided to the user. In other words,
the user will have the information on what the object does instead of how
it does it.
In Java, an abstract class is a class that cannot be instantiated directly and is
often used as a base class for other classes.

It serves as a blueprint for other classes and can contain both concrete
(implemented) methods and abstract (unimplemented) methods.

Abstract methods, on the other hand, are methods declared in an abstract class
that do not have a method body.

Subclasses of an abstract class must provide implementations for all abstract


methods, making them a key part of the subclass's contract.

Abstract Class:
● An abstract class is declared using the abstract keyword.
● Abstract classes can have instance variables, concrete methods (with
implementations), and abstract methods (without implementations).
● Abstract classes cannot be instantiated on their own; they exist to be
subclassed.
Abstract Method:
● An abstract method is declared using the abstract keyword and does not
have a method body.
● Abstract methods are meant to be overridden (implemented) by
subclasses.
● Any class that extends an abstract class with abstract methods must
provide concrete implementations for all those abstract methods.
Program a : Create an online shopping cart system using abstract classes and
methods. Design an abstract class Product with attributes like productName, price, and
quantity, and declare an abstract method calculateTotalPrice(). Implement concrete
subclasses for different types of products, such as Electronics, Clothing, and Books.
Each subclass should provide its own implementation of the calculateTotalPrice()
method based on the product type. Write a program that allows users to add products
to their shopping cart, calculate the total price, and display the items in the cart.

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

// Abstract class representing a general product


abstract class Product {
protected String productName;
protected double price;
protected int quantity;

// Constructor to initialize product attributes


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

// Abstract method that must be implemented by all subclasses


abstract double calculateTotalPrice();

// Method to display product details


public void displayProduct() {
System.out.printf("%-15s | Price: $%.2f | Quantity: %d | Total: $%.2f%n",
productName, price, quantity, calculateTotalPrice());
}
}

// Electronics subclass extending Product


class Electronics extends Product {
private final double taxRate = 0.15; // 15% tax on electronics

public Electronics(String productName, double price, int quantity) {


super(productName, price, quantity);
}

@Override
double calculateTotalPrice() {
return (price * quantity) * (1 + taxRate); // Apply tax
}
}

// Clothing subclass extending Product


class Clothing extends Product {
private final double discount = 0.10; // 10% discount for 3 or more items

public Clothing(String productName, double price, int quantity) {


super(productName, price, quantity);
}

@Override
double calculateTotalPrice() {
if (quantity >= 3) { // Apply discount if quantity is 3 or more
return (price * quantity) * (1 - discount);
}
return price * quantity;
}
}

// Books subclass extending Product


class Books extends Product {
public Books(String productName, double price, int quantity) {
super(productName, price, quantity);
}

@Override
double calculateTotalPrice() {
return price * quantity; // No tax or discount for books
}
}

// ShoppingCart class to manage the cart


class ShoppingCart {
private List<Product> cartItems; // List to store products

// Constructor to initialize the cart


public ShoppingCart() {
this.cartItems = new ArrayList<>();
}

// Method to add a product to the cart


public void addProduct(Product product) {
cartItems.add(product);
System.out.println(product.productName + " added to the cart.");
}

// Method to display all products in the cart


public void displayCart() {
if (cartItems.isEmpty()) {
System.out.println("Your cart is empty.");
return;
}
System.out.println("\n--- Shopping Cart Items ---");
for (Product product : cartItems) {
product.displayProduct();
}
}

// Method to calculate the total price of all products in the cart


public double calculateTotalCartPrice() {
double total = 0;
for (Product product : cartItems) {
total += product.calculateTotalPrice();
}
return total;
}
}

// Main class to run the shopping cart system


public class OnlineShoppingCart {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
ShoppingCart cart = new ShoppingCart(); // Create a shopping cart
while (true) {
// Display menu options
System.out.println("\n--- Online Shopping Cart ---");
System.out.println("1. Add Electronics");
System.out.println("2. Add Clothing");
System.out.println("3. Add Books");
System.out.println("4. View Cart");
System.out.println("5. Checkout");
System.out.println("6. Exit");
System.out.print("Choose an option: ");
int choice = scanner.nextInt();

// Exit condition
if (choice == 6) {
System.out.println("Thank you for shopping!");
break;
}

switch (choice) {
case 1: // Add Electronics
System.out.print("Enter product name: ");
scanner.nextLine(); // Consume newline
String eName = scanner.nextLine();
System.out.print("Enter price: ");
double ePrice = scanner.nextDouble();
System.out.print("Enter quantity: ");
int eQuantity = scanner.nextInt();
cart.addProduct(new Electronics(eName, ePrice, eQuantity));
break;
case 2: // Add Clothing
System.out.print("Enter product name: ");
scanner.nextLine();
String cName = scanner.nextLine();
System.out.print("Enter price: ");
double cPrice = scanner.nextDouble();
System.out.print("Enter quantity: ");
int cQuantity = scanner.nextInt();
cart.addProduct(new Clothing(cName, cPrice, cQuantity));
break;
case 3: // Add Books
System.out.print("Enter book name: ");
scanner.nextLine();
String bName = scanner.nextLine();
System.out.print("Enter price: ");
double bPrice = scanner.nextDouble();
System.out.print("Enter quantity: ");
int bQuantity = scanner.nextInt();
cart.addProduct(new Books(bName, bPrice, bQuantity));
break;
case 4: // View Cart
cart.displayCart();
break;
case 5: // Checkout
cart.displayCart();
System.out.printf("Total Cart Price: $%.2f%n",
cart.calculateTotalCartPrice());
System.out.println("Proceeding to checkout...");
break;
default:
System.out.println("Invalid choice. Please try again.");
}
}

scanner.close(); // Close scanner


}
}
Output :
Abstract Classes and Interfaces:

Inheritance is crucial for abstract classes and interfaces.


➢ Abstract classes can provide a common structure and certain method
implementations, leaving the specific implementation to subclasses.
➢ Interfaces define a contract for implementing classes, and a class can
implement multiple interfaces through inheritance.

Program c : Java Program Demonstrating Abstraction using an Abstract Class

In this program, we use abstraction to define a Vehicle abstract class, which contains
an abstract method start(). The subclasses Car and Bike provide their own
implementations of the start() method.

// Abstract class representing a generic vehicle


abstract class Vehicle {

// Abstract method (must be implemented by subclasses)


abstract void start();

// Concrete method (common to all vehicles)


void stop() {
System.out.println("Vehicle is stopping...");
}
}

// Subclass 1: Car, extending the abstract Vehicle class


class Car extends Vehicle {

// Implementing the abstract start method for Car


@Override
void start() {
System.out.println("Car starts with a key ignition.");
}
}
// Subclass 2: Bike, extending the abstract Vehicle class
class Bike extends Vehicle {

// Implementing the abstract start method for Bike


@Override
void start() {
System.out.println("Bike starts with a kick/self-start.");
}
}

// Main class to demonstrate abstraction


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

// Creating an object of Car using Vehicle reference (Upcasting)


Vehicle myCar = new Car();
myCar.start(); // Calls Car's overridden start method
myCar.stop(); // Calls the inherited stop() method from Vehicle class

// Creating an object of Bike using Vehicle reference (Upcasting)


Vehicle myBike = new Bike();
myBike.start(); // Calls Bike's overridden start method
myBike.stop(); // Calls the inherited stop() method from Vehicle class
}
}

Output :
Program d : Develop an Online Payment System using Abstraction in Java, where
users can choose from three payment methods: Credit Card, UPI, and PayPal. The
system should have an abstract class Payment, which defines a common structure for
all payment methods, including an amount variable and an abstract method
processPayment(). Three concrete subclasses (CreditCardPayment, UPIPayment, and
PayPalPayment) should override this method to implement different payment
processes. Additionally, a paymentSummary() method in the abstract class should
display transaction details, ensuring code reusability. The system should prompt users
for relevant payment details based on their chosen method, securely handling sensitive
data like card numbers by masking them partially.

import java.util.Scanner;

// Abstract class defining the structure of a payment system


abstract class Payment {
protected double amount; // Amount to be paid

// Constructor to initialize the amount


public Payment(double amount) {
this.amount = amount;
}

// Abstract method to be implemented by different payment types


abstract void processPayment();

// Common method to display payment summary


void paymentSummary() {
System.out.println("Payment Summary:");
System.out.println("Amount Paid: $" + amount);
System.out.println("Transaction Completed Successfully.\n");
}
}

// Concrete subclass for Credit Card payment


class CreditCardPayment extends Payment {
private String cardNumber; // Sensitive data (masked)

// Constructor to initialize amount and card number


public CreditCardPayment(double amount, String cardNumber) {
super(amount);
this.cardNumber = cardNumber;
}

@Override
void processPayment() {
// Masking card number for security (show only last 4 digits)
String maskedCard = "**** **** **** " +
cardNumber.substring(cardNumber.length() - 4);
System.out.println("\nProcessing Credit Card Payment...");
System.out.println("Card Number: " + maskedCard);
paymentSummary();
}
}

// Concrete subclass for UPI payment


class UPIPayment extends Payment {
private String upiId;

// Constructor to initialize amount and UPI ID


public UPIPayment(double amount, String upiId) {
super(amount);
this.upiId = upiId;
}

@Override
void processPayment() {
System.out.println("\nProcessing UPI Payment...");
System.out.println("UPI ID: " + upiId);
paymentSummary();
}
}

// Concrete subclass for PayPal payment


class PayPalPayment extends Payment {
private String email;

// Constructor to initialize amount and PayPal email


public PayPalPayment(double amount, String email) {
super(amount);
this.email = email;
}

@Override
void processPayment() {
System.out.println("\nProcessing PayPal Payment...");
System.out.println("PayPal Email: " + email);
paymentSummary();
}
}

// Main class for user interaction


public class OnlinePaymentSystem {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

// Asking user for payment amount


System.out.print("Enter the amount to be paid: $");
double amount = scanner.nextDouble();

// Displaying payment options


System.out.println("\nSelect Payment Method:");
System.out.println("1. Credit Card");
System.out.println("2. UPI");
System.out.println("3. PayPal");
System.out.print("Enter your choice: ");
int choice = scanner.nextInt();
scanner.nextLine(); // Consume newline character

Payment payment = null;

switch (choice) {
case 1:
// Handling Credit Card Payment
System.out.print("Enter Credit Card Number (16 digits): ");
String cardNumber = scanner.nextLine();
payment = new CreditCardPayment(amount, cardNumber);
break;

case 2:
// Handling UPI Payment
System.out.print("Enter UPI ID: ");
String upiId = scanner.nextLine();
payment = new UPIPayment(amount, upiId);
break;

case 3:
// Handling PayPal Payment
System.out.print("Enter PayPal Email: ");
String email = scanner.nextLine();
payment = new PayPalPayment(amount, email);
break;

default:
System.out.println("Invalid choice! Please restart and select a valid payment
method.");
scanner.close();
return;
}

// Processing the chosen payment method


payment.processPayment();
scanner.close();
}
}

Output :
Why use Java interface?
There are mainly three reasons to use interface. They are given below.
○ It is used to achieve abstraction.
○ By interface, we can support the functionality of multiple inheritance.
○ It can be used to achieve loose coupling.
Key Points About Interfaces:
1. An interface can only contain abstract methods (methods without a body)
until Java 8.
2. A class that implements an interface must provide an implementation for all
methods
declared in the interface.
3. A class can implement multiple interfaces, allowing for a form of multiple
inheritance.
Syntax :

Interface <interface_name> {​
// declare constant fields​
// declare methods that abstract ​
// by default. ​
}

Program f : Example of Java interface

interface printable
{
void print();
}
class A6 implements printable{
public void print(){System.out.println("Hello");}
public static void main(String args[])
{
A6 obj = new A6();
obj.print();
}
}
Program g : Create an interface called Animal that declares common behaviors for
animals (eat() and makeSound()). Create two classes—Dog and Cat—that implement
the Animal interface and provide their own implementations for the methods.

// Animal.java - Interface that defines common behaviors for animals


public interface Animal {
// Abstract method for eating behavior
void eat();

// Abstract method for making a sound


void makeSound();
}

// Dog.java - Implements the Animal interface


public class Dog implements Animal {
// Implement the eat() method
@Override
public void eat() {
System.out.println("The dog is eating dog food.");
}

// Implement the makeSound() method


@Override
public void makeSound() {
System.out.println("The dog barks: Woof! Woof!");
}
}

// Cat.java - Implements the Animal interface


public class Cat implements Animal {
// Implement the eat() method
@Override
public void eat() {
System.out.println("The cat is eating cat food.");
}

// Implement the makeSound() method


@Override
public void makeSound() {
System.out.println("The cat meows: Meow! Meow!");
}
}

// MainApp.java - Entry point to test the implementation


public class MainApp {
public static void main(String[] args) {
// Create instances of Dog and Cat
Animal dog = new Dog();
Animal cat = new Cat();

// Call methods on Dog instance


System.out.println("Dog's behavior:");
dog.eat();
dog.makeSound();

System.out.println("\nCat's behavior:");
// Call methods on Cat instance
cat.eat();
cat.makeSound();
}
}

Output :
Program h : Create a Banking System where we manage different types of bank
accounts:
1. Savings Account: Offers interest on the balance.
2. Current Account: No interest but allows overdraft.
Define an interface called BankAccount with methods for basic operations such
asdepositing, withdrawing, and checking balance. Implement these methods in
SavingsAccount and CurrentAccount classes.

// Define the BankAccount interface with common bank account operations


public interface BankAccount {
void deposit(double amount); // Method to deposit money
void withdraw(double amount); // Method to withdraw money
double getBalance(); // Method to check balance
void displayAccountDetails(); // Method to display account details
}

// SavingsAccount class implementing BankAccount interface


public class SavingsAccount implements BankAccount {
private String accountNumber;
private String accountHolderName;
private double balance;
private double interestRate;

// Constructor to initialize savings account


public SavingsAccount(String accountNumber, String accountHolderName, double
interestRate) {
this.accountNumber = accountNumber;
this.accountHolderName = accountHolderName;
this.interestRate = interestRate;
this.balance = 0;
}

// Implement deposit method


@Override
public void deposit(double amount) {
balance += amount;
System.out.println("Deposited: " + amount + ", New Balance: " + balance);
}
// Implement withdraw method
@Override
public void withdraw(double amount) {
if (amount <= balance) {
balance -= amount;
System.out.println("Withdrawn: " + amount + ", New Balance: " + balance);
} else {
System.out.println("Insufficient balance for withdrawal.");
}
}

// Implement getBalance method


@Override
public double getBalance() {
return balance;
}

// Implement displayAccountDetails method


@Override
public void displayAccountDetails() {
System.out.println("Savings Account - Account Number: " + accountNumber +
", Holder: " + accountHolderName +
", Balance: " + balance +
", Interest Rate: " + interestRate + "%");
}

// Method to apply interest to the savings account balance


public void applyInterest() {
double interest = balance * (interestRate / 100);
balance += interest;
System.out.println("Interest applied: " + interest + ", New Balance: " + balance);
}
}

// CurrentAccount class implementing BankAccount interface


public class CurrentAccount implements BankAccount {
private String accountNumber;
private String accountHolderName;
private double balance;
private double overdraftLimit;
// Constructor to initialize current account
public CurrentAccount(String accountNumber, String accountHolderName, double
overdraftLimit) {
this.accountNumber = accountNumber;
this.accountHolderName = accountHolderName;
this.overdraftLimit = overdraftLimit;
this.balance = 0;
}

// Implement deposit method


@Override
public void deposit(double amount) {
balance += amount;
System.out.println("Deposited: " + amount + ", New Balance: " + balance);
}

// Implement withdraw method with overdraft limit check


@Override
public void withdraw(double amount) {
if (balance - amount >= -overdraftLimit) {
balance -= amount;
System.out.println("Withdrawn: " + amount + ", New Balance: " + balance);
} else {
System.out.println("Withdrawal exceeds overdraft limit.");
}
}

// Implement getBalance method


@Override
public double getBalance() {
return balance;
}

// Implement displayAccountDetails method


@Override
public void displayAccountDetails() {
System.out.println("Current Account - Account Number: " + accountNumber +
", Holder: " + accountHolderName +
", Balance: " + balance +
", Overdraft Limit: " + overdraftLimit);
}
}

// BankingApp class containing the main method for execution


public class BankingApp {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

// Create a Savings Account and perform transactions


SavingsAccount savingsAccount = new SavingsAccount("S12345", "John Doe",
5.0);
savingsAccount.deposit(1000);
savingsAccount.applyInterest();
savingsAccount.withdraw(500);
savingsAccount.displayAccountDetails();

System.out.println("\n-------------------------\n");

// Create a Current Account and perform transactions


CurrentAccount currentAccount = new CurrentAccount("C67890", "Jane Smith",
1000);
currentAccount.deposit(2000);
currentAccount.withdraw(2500);
currentAccount.displayAccountDetails();

System.out.println("\n-------------------------\n");

// Interactive Banking Operations for Savings Account


System.out.println("Interactive Banking - Savings Account:");
System.out.println("Enter amount to deposit:");
double depositAmount = scanner.nextDouble();
savingsAccount.deposit(depositAmount);

System.out.println("Enter amount to withdraw:");


double withdrawAmount = scanner.nextDouble();
savingsAccount.withdraw(withdrawAmount);

savingsAccount.displayAccountDetails();
scanner.close();
}
}

Output :

Program i : Create a simple music player application using interfaces. Design an


interface Playable with methods like play(), pause(), and stop(). Implement classes
MP3Player and CDPlayer that implement the Playable interface. These classes should
provide their own implementations for playing, pausing, and stopping music. Write a
program that simulates a music player, allowing users to control playback for both
MP3 and CD players.

// Define an interface Playable with common music player methods


public interface Playable {
void play(); // Method to start playing music
void pause(); // Method to pause music
void stop(); // Method to stop music
}

// MP3Player class implementing the Playable interface


public class MP3Player implements Playable {
@Override
public void play() {
System.out.println("MP3 Player is playing music...");
}

@Override
public void pause() {
System.out.println("MP3 Player is paused.");
}

@Override
public void stop() {
System.out.println("MP3 Player has stopped playing music.");
}
}

// CDPlayer class implementing the Playable interface


public class CDPlayer implements Playable {
@Override
public void play() {
System.out.println("CD Player is playing music...");
}

@Override
public void pause() {
System.out.println("CD Player is paused.");
}

@Override
public void stop() {
System.out.println("CD Player has stopped playing music.");
}
}

// MusicPlayerApp class containing the main method to test the implementation


import java.util.Scanner;

public class MusicPlayerApp {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
Playable player;

System.out.println("Choose your music player: 1. MP3 Player 2. CD Player");


int choice = scanner.nextInt();

if (choice == 1) {
player = new MP3Player();
} else {
player = new CDPlayer();
}

// Simulating music player operations


player.play();
System.out.println("Press Enter to pause...");
scanner.nextLine(); // Consume newline
scanner.nextLine(); // Wait for user input
player.pause();

System.out.println("Press Enter to stop...");


scanner.nextLine(); // Wait for user input
player.stop();

scanner.close();
}
}

Output :

Program j : Develop a vehicle inventory system using interfaces. Design an interface


Vehicle with methods like start(), stop(), and getFuelLevel(). Implement classes Car,
Motorcycle, and Truck that implement the Vehicle interface. Each class should
provide its own implementations for starting, stopping, and getting the fuel level of
the vehicle. Create a program that manages a vehicle inventory, allowing users to
perform actions such as starting, stopping, and checking fuel levels for different types
of vehicles.

// Define an interface Vehicle with common vehicle methods


public interface Vehicle {
void start(); // Method to start the vehicle
void stop(); // Method to stop the vehicle
double getFuelLevel(); // Method to check the fuel level
}

// Car class implementing the Vehicle interface


public class Car implements Vehicle {
private double fuelLevel;

public Car(double fuelLevel) {


this.fuelLevel = fuelLevel;
}

@Override
public void start() {
System.out.println("Car is starting...");
}

@Override
public void stop() {
System.out.println("Car has stopped.");
}

@Override
public double getFuelLevel() {
return fuelLevel;
}
}

// Motorcycle class implementing the Vehicle interface


public class Motorcycle implements Vehicle {
private double fuelLevel;

public Motorcycle(double fuelLevel) {


this.fuelLevel = fuelLevel;
}

@Override
public void start() {
System.out.println("Motorcycle is starting...");
}

@Override
public void stop() {
System.out.println("Motorcycle has stopped.");
}

@Override
public double getFuelLevel() {
return fuelLevel;
}
}

// Truck class implementing the Vehicle interface


public class Truck implements Vehicle {
private double fuelLevel;

public Truck(double fuelLevel) {


this.fuelLevel = fuelLevel;
}

@Override
public void start() {
System.out.println("Truck is starting...");
}

@Override
public void stop() {
System.out.println("Truck has stopped.");
}

@Override
public double getFuelLevel() {
return fuelLevel;
}
}

// VehicleInventoryApp class containing the main method to test the implementation


import java.util.Scanner;

public class VehicleInventoryApp {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
Vehicle vehicle;

System.out.println("Choose a vehicle: 1. Car 2. Motorcycle 3. Truck");


int choice = scanner.nextInt();

switch (choice) {
case 1:
vehicle = new Car(50);
break;
case 2:
vehicle = new Motorcycle(15);
break;
case 3:
vehicle = new Truck(80);
break;
default:
System.out.println("Invalid choice.");
scanner.close();
return;
}

// Simulating vehicle operations


vehicle.start();
System.out.println("Fuel Level: " + vehicle.getFuelLevel() + " liters");

System.out.println("Press Enter to stop the vehicle...");


scanner.nextLine(); // Consume newline
scanner.nextLine(); // Wait for user input
vehicle.stop();

scanner.close();
}
}

Output :

Conclusion : Thus, we have successfully implemented abstraction.

You might also like