1Z0-809 · Question #65
Given the code format: ``java class DBConfiguration { String user; String password; } ` And the following partial class definition for DBHandler: `java public class DBHandler { DBConfiguration…
The correct answer is C. return new DBConfiguration. Option C (return new DBConfiguration;) is the only choice that both creates an instance of DBConfiguration and returns it - which is exactly what the method signature demands, since configureDB declares DBConfiguration as its return type. In Java, a non-void method must have a…
Question
class DBConfiguration {
String user;
String password;
}
And the following partial class definition for DBHandler:
public class DBHandler {
DBConfiguration configureDB (String uname, String password) {
// insert code here (line 6)
}
public static void main (String[] args) {
DBHandler r = new DBHandler();
DBConfiguration dbConf = r.configureDB ("manager", "manager");
}
}
Which code fragment must be inserted at line 6 to enable the code to compile?Options
- ADBConfiguration f;
- Breturn DBConfiguration;
- Creturn new DBConfiguration;
- DRetutn 0;
How the community answered
(54 responses)- A13% (7)
- B4% (2)
- C80% (43)
- D4% (2)
Explanation
Option C (return new DBConfiguration;) is the only choice that both creates an instance of DBConfiguration and returns it - which is exactly what the method signature demands, since configureDB declares DBConfiguration as its return type. In Java, a non-void method must have a return statement that hands back a value of the declared type, and new DBConfiguration (intended as new DBConfiguration()) is how you instantiate an object and pass it back to the caller.
Why the distractors fail:
- A (
DBConfiguration f;) merely declares a local variable without ever returning anything - the compiler will reject a non-void method with no return statement. - B (
return DBConfiguration;) attempts to return the class name (a type), not an instance of that class - types are not values you can return. - D (
return 0;) returns anintliteral, which is incompatible with theDBConfigurationreturn type - Java is statically typed and will reject the mismatch.
Memory tip: Think of the return type in the method signature as a promise - if you promise to return a DBConfiguration, you must use new to create one and then return it. Whenever return type ≠ void, ask yourself: "Am I returning a fresh instance (new) or an existing variable of that exact type?"
Community Discussion
No community discussion yet for this question.