Java Technical Interview Practice Test

Session length

1 / 20

What is one restriction of using a static method in Java?

It can use the 'this' reference

It cannot use instance variables without creating an instance

The assertion that static methods in Java cannot use instance variables without creating an instance is indeed correct. Static methods belong to the class rather than to any specific instance of the class. As a result, they do not have access to instance variables, which are tied to individual objects.

To utilize instance variables, an object of the class must be instantiated. This is due to the fact that static methods do not maintain a reference to the instance (or object) they belong to because they can be called independently of an instance. Therefore, if a static method tries to access instance variables directly, it fails, necessitating the creation of an instance to access those variables.

The other options present different scenarios that are not consistent with the behavior of static methods. Static methods indeed cannot use the 'this' reference since 'this' refers to the current instance of the class. They also cannot override instance methods because overriding requires a method defined in a superclass to be overridden in a subclass, and static methods do not fulfill this condition. Lastly, static methods can certainly be declared public, so their accessibility is not a restriction.

It can override instance methods

It cannot be declared public

Next Question
Subscribe

Get the latest from Passetra

You can unsubscribe at any time. Read our privacy policy