Java Class Problem
This Java code defines an interface Payment
and two classes CreditCardPayment
and PayPalPayment
that implement this interface.
The Payment
interface declares a method processPayment(double amount)
which is implemented by both CreditCardPayment
and PayPalPayment
classes.
In the CreditCardPayment
class, there are private fields cardNumber
and cardHolderName
along with a constructor to initialize them. It also implements the processPayment
method to print a message indicating the processing of a credit card payment along with the card number and card holder name.
Similarly, the PayPalPayment
class has a private field email
and a constructor to initialize it. It implements the processPayment
method to print a message indicating the processing of a PayPal payment along with the email.
The Main
class contains the main
method which serves as the entry point of the program. It prompts the user to input the payment amount, credit card details (card number and card holder name), and PayPal email using a Scanner
. Then, it creates instances of CreditCardPayment
and PayPalPayment
classes with the provided details and calls the processPayment
method on each instance to simulate the processing of the payments.
Finally, the Scanner
object is closed to release system resources.
package imran;
import java.util.Scanner;
interface Payment {
void processPayment(double amount);
}
class CreditCardPayment implements Payment {
private String cardNumber;
private String cardHolderName;
public CreditCardPayment(String cardNumber, String cardHolderName) {
this.cardNumber = cardNumber;
this.cardHolderName = cardHolderName;
}
@Override
public void processPayment(double amount) {
System.out.println("Processing credit card payment of RS " + amount + " by card number " + cardNumber + " (Card Holder: " + cardHolderName + ")");
}
}
class PayPalPayment implements Payment {
private String email;
public PayPalPayment(String email) {
this.email = email;
}
@Override
public void processPayment(double amount) {
System.out.println("Processing PayPal payment of " + amount + " for email " + email);
}
}
class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter your payment amount: ");
double amount = scanner.nextDouble();
scanner.nextLine();
System.out.print("Enter your credit card number: ");
String cardNumber = scanner.nextLine();
System.out.print("Enter your card holder name: ");
String cardHolderName = scanner.nextLine();
System.out.print("Enter PayPal email: ");
String email = scanner.nextLine();
CreditCardPayment c = new CreditCardPayment(cardNumber, cardHolderName);
PayPalPayment p = new PayPalPayment(email);
c.processPayment(amount);
p.processPayment(amount);
scanner.close();
}
}