nerdexam
Oracle

1Z0-808 · Question #84

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…

The correct answer is D. blackCowboyHat.setName("Cowboy Hat"). Option D is correct because setName("Cowboy Hat") is an instance method on the Hat class, and it must be called on a specific object reference - blackCowboyHat - using dot notation: blackCowboyHat.setName("Cowboy Hat"). Option A fails on two counts: Java method calls require…

Working with Methods and Encapsulation

Question

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

(42 responses)
  • A
    2% (1)
  • B
    5% (2)
  • C
    7% (3)
  • D
    86% (36)

Explanation

Option D is correct because setName("Cowboy Hat") is an instance method on the Hat class, and it must be called on a specific object reference - blackCowboyHat - using dot notation: blackCowboyHat.setName("Cowboy Hat").

Option A fails on two counts: Java method calls require parentheses (), and Java is case-sensitive (SetName is not the same as setName). Option B omits the object reference entirely - bare method calls like this are only valid inside the same class, not from TestHat. Option C uses the class name Hat instead of the object instance; this syntax is only valid for static methods, and setName is not static.

Memory tip: Think of it as addressing a letter - you need both the recipient (the object instance, blackCowboyHat) and the message (the method call with parentheses, .setName(...)). No recipient, no delivery.

Topics

#method invocation#instance methods#object method calls#encapsulation

Community Discussion

No community discussion yet for this question.

Full 1Z0-808 Practice