Which is true? (Choose all that apply.)
-
"X extends Y" is correct if and only if X is a class and Y is an interface
-
"X extends Y" is correct if and only if X is an interface and Y is a class
-
"X extends Y" is correct if X and Y are either both classes or both interfaces
-
"X extends Y" is correct for all combinations of X and Y being classes and/or interfaces
In Java, 'extends' is used for both class inheritance and interface extension, but the types must match. A class can extend another class, and an interface can extend another interface. Option C correctly states that X extends Y works when both are classes or both are interfaces. Options A and B are wrong because a class cannot extend an interface (that's 'implements'), and an interface cannot extend a class. Option D is wrong because mixing classes and interfaces with 'extends' is invalid.
To answer this question, we need to understand the concept of inheritance in object-oriented programming.
In object-oriented programming, the keyword "extends" is used to establish an inheritance relationship between classes and interfaces. Here are the explanations for each option:
Option A) "X extends Y" is correct if and only if X is a class and Y is an interface. This option is incorrect. In Java, a class can extend another class or implement an interface. The keyword "extends" is used for class inheritance, while the keyword "implements" is used for interface implementation.
Option B) "X extends Y" is correct if and only if X is an interface and Y is a class. This option is incorrect. In Java, an interface cannot extend a class. It can only extend another interface using the keyword "extends".
Option C) "X extends Y" is correct if X and Y are either both classes or both interfaces. This option is correct. In Java, a class can extend another class, and an interface can extend another interface. Therefore, "X extends Y" is correct if X and Y are either both classes or both interfaces.
Option D) "X extends Y" is correct for all combinations of X and Y being classes and/or interfaces. This option is incorrect. As explained above, "X extends Y" is not correct for all combinations. It is only correct if X and Y are either both classes or both interfaces.
Therefore, the correct answer is option C.