Skip to content

Commit acb2e8c

Browse files
committed
feat: add ThisWord example demonstrating usage of 'this' keyword in constructors
Implemented ThisWord.java to illustrate how the 'this' keyword differentiates instance variables from constructor parameters. Includes an example of object creation and field initialization representing an account holder scenario. Signed-off-by: https://github.com/Someshdiwan <[email protected]>
1 parent e4b93dc commit acb2e8c

File tree

1 file changed

+19
-0
lines changed

1 file changed

+19
-0
lines changed
Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
class ThisWord {
2+
// Instance variables for the account holder's name and balance
3+
String accountHolderName;
4+
double accountBalance;
5+
6+
// Parameterized constructor to initialize name and balance using 'this' keyword
7+
public ThisWord(String name, double balance) {
8+
this.accountHolderName = name; // 'this' refers to the instance variable accountHolderName
9+
this.accountBalance = balance; // 'this' refers to the instance variable accountBalance
10+
}
11+
12+
public static void main(String[] args) {
13+
// Create an object of ThisWord class with a parameterized constructor
14+
ThisWord account = new ThisWord("Alice", 1500.0); // Initializing with name and balance
15+
16+
System.out.println("Account Holder: " + account.accountHolderName); // Accessing the name
17+
System.out.println("Account Balance: " + account.accountBalance); // Accessing the balance
18+
}
19+
}

0 commit comments

Comments
 (0)