CJCoding With Joseph
15per day
← Back to Question List
Java Code Walkthrough #35

this Keyword Fixes Hidden Field

mediumClasses (and Objects)

📄 Code

Read carefully — what does this print?
1class Counter {
2 private int value;
3 
4 public Counter(int value) {
5 this.value = value;
6 }
7 
8 public void add(int value) {
9 this.value = this.value + value;
10 }
11 
12 public int getValue() {
13 return value;
14 }
15}
16 
17public class Main {
18 public static void main(String[] args) {
19 Counter c = new Counter(5);
20 c.add(3);
21 c.add(2);
22 System.out.println(c.getValue());
23 }
24}

🎯 Your Answer