1Z0-803 · Question #113
Given the code fragments: 9. class Student { 10. int rollnumber; 11. String name; 12. List courses = new ArrayList(); 13. // insert code fragment here 14. public String toString() { 15. return rollnum
The correct answer is C. Student(int i, String name, List cs) {. This question requires identifying the correct Java constructor definition that allows the Student class to be instantiated with specific arguments from another class.
Question
Options
- Aprivate Student(int i, String name, List cs) {
- Bpublic void Student(int i, String name, List cs) {
- CStudent(int i, String name, List cs) {
- DStudent(int i, String name, ArrayList cs) {
How the community answered
(38 responses)- A3% (1)
- B13% (5)
- C79% (30)
- D5% (2)
Why each option
This question requires identifying the correct Java constructor definition that allows the `Student` class to be instantiated with specific arguments from another class.
The `private` access modifier makes the constructor inaccessible from the `Test` class (assuming they are not nested or in the same class), leading to a compilation error when `Test` attempts to instantiate `Student`.
Including `void` as a return type transforms this into a regular method named `Student`, not a constructor, thus preventing `new Student()` from being recognized as an object creation call.
The fragment `Student(int i, String name, List cs)` defines a constructor with the correct class name, no return type, and parameter types (`int`, `String`, `List`) that precisely match the `new Student(123,"Fred",cs)` call in the `Test` class, utilizing default (package-private) accessibility.
Declaring the parameter as `ArrayList cs` would require the argument in `new Student()` to be of type `ArrayList`, or explicitly cast to `ArrayList`, which is not done by the `List cs = new ArrayList();` declaration and usage in the `Test` class.
Concept tested: Java constructor syntax and access modifiers
Source: https://docs.oracle.com/javase/tutorial/java/javaOO/constructors.html
Topics
Community Discussion
No community discussion yet for this question.