this is a one of the keyword amongst the other in java, and java objects includes a data member this thats actually a reference to the current object. this keyword is useful if you need to refer to the current object - e.g. when you want to pass the current object to the method or constructor of class.
to understand more look at below code snippet in which a class Number has method printNumber() which prints the value stored in class variable mValue, with the help of NumberPrinter class, which takes the reference of Number class in its constructor.
printNumber() method creates the instance of NumberPrinter and pass its own reference in the form of this.
Output:
to understand more look at below code snippet in which a class Number has method printNumber() which prints the value stored in class variable mValue, with the help of NumberPrinter class, which takes the reference of Number class in its constructor.
printNumber() method creates the instance of NumberPrinter and pass its own reference in the form of this.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class Number { | |
//class variable to store number | |
private int mValue; | |
public Number(int val) { | |
mValue = val; | |
} | |
public int getValue() { | |
return mValue; | |
} | |
//prints the number with NumberPrinter | |
public void printNumber() { | |
//pass the referrence current Number object in the form of "this", to the constructor of NumberPrinter | |
NumberPrinter printer = new NumberPrinter(this); | |
printer.print(); | |
} | |
//class prints Number object on the screen, takes the Number objects referrence | |
public class NumberPrinter { | |
//class variable to store Number object referrence | |
private Number mNumber; | |
public NumberPrinter(Number number) { | |
this.mNumber = number; | |
} | |
public void print() { | |
System.out.println("Number : " + mNumber.getValue()); | |
} | |
} | |
public static void main(String args[]) { | |
Number number = new Number(101); | |
number.printNumber(); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Number : 101 | |
Process finished with exit code 0 |
Comments
Post a Comment