Skip to content
Sharp

Object-oriented programming · interview question

In the following code snippet, why does using 'this' cause a compile error? public class Store { private String name; public static void updateStoreName(String newName) { this.name = newName; } }?

Multiple choiceHardchapter-2-curatedpremiumoopthis-keyword
java
public class Store {
  private String name;
  public static void updateStoreName(String newName) {
    this.name = newName;
  }
}
Choose one answer
Answer and explanation

Correct answer

A. 'this' cannot be used in a static context

Why

The 'this' keyword cannot be used in a static method because 'this' refers to an instance of the class, and static methods do not operate on a specific instance.

Test yourself on Object-oriented programming

A free test with instant, explained results. No account needed.

Start free test
All Object-oriented programming questions →