Skip to content

Commit fb20c7b

Browse files
committed
feat: Add Test class using 'this' keyword to assign instance variables
WHAT the code does: Introduces a Test class with fields x, y, and res. Defines getData(int x, int y) to assign method parameters to instance variables using the this keyword. Defines display() to compute the sum of x and y and print the result. Provides a JavKeyword1 driver class with main() that creates a Test object, sets data, and displays the sum. WHY this matters: Demonstrates correct handling of variable shadowing in Java. Shows how the this keyword resolves ambiguity when method parameters share names with instance variables. Reinforces understanding of object state management across method calls. Useful for beginners to distinguish between local scope and object fields. HOW it works: A Test object is instantiated in main(). getData(5,7) is called, binding parameters to the instance variables via this.x and this.y. display() calculates res = x + y and prints the sum (12). The this keyword ensures the instance fields are updated rather than the local method parameters. Tips and gotchas: If method parameters had different names, this keyword would not be required but is often kept for clarity. Leaving out this in shadowing cases would assign values to the method parameters only, leaving object fields unchanged. this can also be used to call constructors or pass the current object as an argument. Use-cases: Teaching example for scope resolution and the role of this in Java. Foundation for object state manipulation in larger programs. Helps explain why constructor parameters often use the same names as fields. Short key: class-test this-keyword variable-shadowing. Signed-off-by: https://github.com/Someshdiwan <[email protected]>
1 parent 62fcbee commit fb20c7b

File tree

1 file changed

+8
-13
lines changed

1 file changed

+8
-13
lines changed
Lines changed: 8 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,24 +1,19 @@
1-
class Test
2-
{
1+
class Test {
32
int x, y, res;
4-
void getData(int x, int y)
5-
{
6-
this.x = x; //this is a keyword here
3+
4+
void getData(int x, int y) {
5+
this.x = x; // 'this' it is keyword.
76
this.y = y;
87
}
9-
void display()
10-
{
8+
void display() {
119
res = x+y;
1210
System.out.println(res);
1311
}
1412
}
15-
16-
class JavKeyword1
17-
{
18-
public static void main(String[] args)
19-
{
13+
class JavKeyword1 {
14+
public static void main(String[] args) {
2015
Test t = new Test();
2116
t.getData(5,7);
2217
t.display();
2318
}
24-
}
19+
}

0 commit comments

Comments
 (0)