educative.io

Educative

Class Payment is abstract and cannot be instantiated, so how can it be an attribute of the ParkingTicket class?

The class Payment is abstract and therefore cannot be instantiated, yet in the skeleton code for the ParkingTicket class, it is declared as a field:

private Payment payment;

I don’t think that would compile? Would we have to add the following two attributes to ParkingTicket instead:

private Cash cashPayment;
private CreditCard creditCardPayment;


Course: Grokking the Low Level Design Interview Using OOD Principles - Learn Interactively
Lesson: https://www.educative.io/courses/grokking-the-low-level-design-interview-using-ood-principles/7D6XVRqxXVj

1 Like

Hi @Yunfei_Xie,

You are correct that an abstract class cannot be instantiated directly. However, it can be used as a type for a field or parameter, which is what is happening in this case. Declaring the field “private Payment payment” in the ParkingTicket class is valid, as long as it is initialized with a non-abstract subclass of Payment when an instance of ParkingTicket is created. For example, if two concrete classes extend Payment, such as Cash and CreditCard , then an instance of one of these classes can be assigned to the payment field:
ParkingTicket ticket = new ParkingTicket();
Payment payment = new Cash(); // or new CreditCard()
ticket.setPayment(payment);

Note: Adding separate fields for each payment type, such as “private Cash cashPayment” and “private CreditCard creditCardPayment”, would work but could become unwieldy if there are many payment methods. Using the Payment abstract class as the type for the field provides more flexibility and allows for simpler code.

Happy Learning :slight_smile:

Thank you for the detailed answer. Really appreciate it.


Course: Grokking the Low Level Design Interview Using OOD Principles - Learn Interactively
Lesson: https://www.educative.io/courses/grokking-the-low-level-design-interview-using-ood-principles/7D6XVRqxXVj

1 Like