nerdexam
Oracle

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.

Working with Methods and Encapsulation

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)
  • A
    6% (4)
  • B
    2% (1)
  • C
    3% (2)
  • D
    89% (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.

AblackCowboyHat.setName = "Cowboy Hat";

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.

BsetName("Cowboy Hat");

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.

CHat.setName("Cowboy Hat");

`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.

DblackCowboyHat.setName("Cowboy Hat");Correct

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

#object instantiation#instance methods#setter methods

Community Discussion

No community discussion yet for this question.

Full 1Z0-803 Practice