Given: 11. class ClassA {} 12. class ClassB extends ClassA {} 13. class ClassC extends ClassA {} and: 21. ClassA p0 = new ClassA(); 22. ClassB p1 = new ClassB(); 23. ClassC p2 = new ClassC(); 24. ClassA p3 = new ClassB(); 25. ClassA p4 = new ClassC(); Which three are valid? (Choose three.)

  1. p0 = p1;

  2. p1 =p2;

  3. p2 = p4;

  4. p2 = (ClassC)p1;

  5. p1 = (ClassB)p3;

  6. p2 = (ClassC)p4;


Correct Option: A,E,F

AI Explanation

To determine which options are valid, let's go through each option and analyze whether the assignment is valid or not.

Option A) p0 = p1; This assignment is valid. Since ClassB extends ClassA, an object of ClassB can be assigned to a reference variable of type ClassA.

Option B) p1 = p2; This assignment is invalid. ClassB and ClassC are sibling classes that both extend ClassA. They are not in an inheritance relationship with each other. Therefore, an object of ClassC cannot be assigned to a reference variable of type ClassB.

Option C) p2 = p4; This assignment is invalid. Similar to option B, ClassC and ClassA are sibling classes. They are not in an inheritance relationship with each other. Therefore, an object of ClassA cannot be assigned to a reference variable of type ClassC.

Option D) p2 = (ClassC)p1; This assignment is invalid. Although ClassB extends ClassA, and ClassC extends ClassA, ClassB and ClassC are sibling classes and not in an inheritance relationship with each other. Therefore, an object of ClassB cannot be cast to ClassC.

Option E) p1 = (ClassB)p3; This assignment is valid. Since ClassB extends ClassA, and p3 refers to an object of ClassB, it is valid to cast p3 to ClassB and assign it to p1.

Option F) p2 = (ClassC)p4; This assignment is valid. Since ClassC extends ClassA, and p4 refers to an object of ClassC, it is valid to cast p4 to ClassC and assign it to p2.

Therefore, the three valid options are A, E, and F.

Find more quizzes: