1Z0-803 · Question #100
View the Exhibit. public class Hat { public int ID =0; public String name = "hat"; public String size = "One Size Fit All"; public String color=""; public String getName() { return name; } public void
The correct answer is D. blackCowboyHat.setName("Cowboy Hat");. To set the name of a Hat instance, you must invoke the setName instance method directly on the blackCowboyHat object using dot notation and pass the desired string as an argument.
Question
View the Exhibit. public class Hat { public int ID =0; public String name = "hat"; public String size = "One Size Fit All"; public String color=""; public String getName() { return name; } public void setName(String name) { this.name = name; } } Given:
public class TestHat { public static void main(String[] args) { Hat blackCowboyHat = new Hat(); } } Which statement sets the name of the Hat instance?
Options
- AblackCowboyHat.setName = "Cowboy Hat";
- BsetName("Cowboy Hat");
- CHat.setName("Cowboy Hat");
- DblackCowboyHat.setName("Cowboy Hat");
How the community answered
(64 responses)- A6% (4)
- B2% (1)
- C3% (2)
- D89% (57)
Why each option
To set the name of a `Hat` instance, you must invoke the `setName` instance method directly on the `blackCowboyHat` object using dot notation and pass the desired string as an argument.
This syntax attempts to assign a string value directly to a method reference, `setName`, which is syntactically incorrect for calling a method or setting a field with a method-like name.
Calling `setName("Cowboy Hat")` directly without an object reference would imply a call to a method within the current scope, not on the `blackCowboyHat` instance.
`Hat.setName("Cowboy Hat")` attempts to call `setName` as a static method on the `Hat` class itself, but `setName` is defined as an instance method, not a static one.
This statement correctly calls the `setName` instance method on the `blackCowboyHat` object, passing "Cowboy Hat" as the string argument to modify the instance's `name` field. The syntax `objectReference.methodName(arguments)` is the standard way to invoke an instance method.
Concept tested: Invoking instance methods on objects
Source: https://docs.oracle.com/javase/tutorial/java/javaOO/methods.html
Topics
Community Discussion
No community discussion yet for this question.