Using this reference in java described with program

0




The this Reference

Two uses of the this keyword are:

● To resolve ambiguity between instance variables and parameters

● To pass the current object as a parameter to another method

Code provides a class definition that demonstrates these uses. The MyDate class declares instance variables, Lines 2–4. One of the parameters to one of the constructors (Lines 6–10) is also called day, so in that context, the keyword this resolves the ambiguity (Line 7). The addDays method creates a new date object (Line 18). In this constructor call, the method uses the this keyword as an argument to refer to the current object.

Code The Use of the this Keyword

1 public class MyDate {

2 private int day = 1;

3 private int month = 1;

4 private int year = 2000;

5

6 public MyDate(int day, int month, int year) {

7 this.day = day;

8 this.month = month;

9 this.year = year;

10 }

11 public MyDate(MyDate date) {

12 this.day = date.day;

13 this.month = date.month;

14 this.year = date.year;

15 }

16

17 public MyDate addDays(int moreDays) {

18 MyDate newDate = new MyDate(this);

19 newDate.day = newDate.day + moreDays;

20 // Not Yet Implemented: wrap around code…

21 return newDate;

22 }

23 public String toString() {

24 return “” + day + “-” + month + “-” + year;

25 }

26 }