Core Java · interview question
Why does the following code throw a ClassCastException at runtime? class Payment {} class CreditCardPayment extends Payment {} class CashPayment extends Payment {} public class Main { public static void main(String[] args) { Payment p = new CreditCardPayment(); CashPayment cp = (CashPayment) p; } }?
Multiple choiceHardchapter-5-curatedpremiumcore-javaupcasting-and-dynamic-dispatch
class Payment {}
class CreditCardPayment extends Payment {}
class CashPayment extends Payment {}
public class Main { public static void main(String[] args) { Payment p = new CreditCardPayment(); CashPayment cp = (CashPayment) p; } }Answer and explanation
Correct answer
B. A CreditCardPayment object cannot be cast to a CashPayment object.
Why
A ClassCastException occurs because a CreditCardPayment object cannot be cast to a CashPayment object, as they are not in the same inheritance hierarchy directly. The runtime type of the object must be compatible with the cast type.
Test yourself on Core Java
A free test with instant, explained results. No account needed.
More Core Java questions
- What happens if a class implements two interfaces that have methods with the same signature?
- Given the code snippet below, what will be the result of the comparison using '=='?
- Which of the following variable names is best for storing the total amount in a shopping cart?
- When does a local variable declared inside a method stop existing?
- Which of the following is a checked exception?
- Why might you choose 'int' over 'long' for storing the number of items in a small store's inventory?