5JAVA.docx
5JAVA.docx
like default and static methods. Show polymorphism with overriding methods.
Theory :
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.
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;
@Override
double calculateTotalPrice() {
return (price * quantity) * (1 + taxRate); // Apply tax
}
}
@Override
double calculateTotalPrice() {
if (quantity >= 3) { // Apply discount if quantity is 3 or more
return (price * quantity) * (1 - discount);
}
return price * quantity;
}
}
@Override
double calculateTotalPrice() {
return price * quantity; // No tax or discount for books
}
}
// 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.");
}
}
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.
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;
@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();
}
}
@Override
void processPayment() {
System.out.println("\nProcessing UPI Payment...");
System.out.println("UPI ID: " + upiId);
paymentSummary();
}
}
@Override
void processPayment() {
System.out.println("\nProcessing PayPal Payment...");
System.out.println("PayPal Email: " + email);
paymentSummary();
}
}
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;
}
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.
}
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.
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.
System.out.println("\n-------------------------\n");
System.out.println("\n-------------------------\n");
savingsAccount.displayAccountDetails();
scanner.close();
}
}
Output :
@Override
public void pause() {
System.out.println("MP3 Player is paused.");
}
@Override
public void stop() {
System.out.println("MP3 Player has stopped 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.");
}
}
if (choice == 1) {
player = new MP3Player();
} else {
player = new CDPlayer();
}
scanner.close();
}
}
Output :
@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;
}
}
@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;
}
}
@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;
}
}
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;
}
scanner.close();
}
}
Output :