1Z0-803 · Question #130
Given the code fragment: Which two code fragments, inserted independently, enable the code to compile?
The correct answer is A. t.fvar = 200; D. t.fvar = 200;. To assign a value to an instance variable fvar of an object t, accessing it directly through the object reference t.fvar is a valid method.
Question
Given the code fragment:
Which two code fragments, inserted independently, enable the code to compile?
Exhibit
Options
- At.fvar = 200;
- Bfvar = 200;
- Cthis.fvar = 200;
- Dt.fvar = 200;
- Ethis.fvar = 200;
How the community answered
(34 responses)- A71% (24)
- B3% (1)
- C18% (6)
- E9% (3)
Why each option
To assign a value to an instance variable `fvar` of an object `t`, accessing it directly through the object reference `t.fvar` is a valid method.
The code fragment `t.fvar = 200;` correctly assigns the value 200 to the instance variable `fvar` of the object referenced by `t`. This is the standard way to access and modify an instance variable of a specific object, particularly from a static context or from outside the object's immediate scope.
`fvar = 200;` attempts to access `fvar` directly without an object reference. This would only compile if `fvar` were a static variable or if the assignment was within a non-static method of the class defining `fvar` without explicit object reference.
`this.fvar = 200;` attempts to assign to `fvar` using the `this` keyword. The `this` keyword refers to the current object instance and can only be used within a non-static context, such as a non-static method or constructor.
The code fragment `t.fvar = 200;` is identical to option A and also correctly assigns the value 200 to the instance variable `fvar` of the object referenced by `t`.
`this.fvar = 200;` is identical to option C and attempts to assign to `fvar` using the `this` keyword, which is only valid within a non-static context.
Concept tested: Accessing instance variables
Source: https://docs.oracle.com/javase/tutorial/java/javaOO/variables.html
Topics
Community Discussion
No community discussion yet for this question.
