1public class Point {
2 public int x = 0;
3 public int y = 0;
4
5 //constructor
6 public Point(int x, int y) {
7 this.x = x;
8 this.y = y;
9 }
10}
11
1this() : used for calling the constructor .
2 we can only use it in the constructor
3this. : used for calling the instance variables
4we can use in any object instances
5
1// java program using ‘this’ keyword
2class Demo
3{
4 int m;
5 int n;
6 public void setValue(int m, int n)
7 {
8 // java this keyword
9 this.m = m;
10 this.n = n;
11 }
12 public void showValue()
13 {
14 System.out.println("Value m = " + m);
15 System.out.println("Value n = " + n);
16 }
17}
18public class ThisExample
19{
20 public static void main(String[] args)
21 {
22 Demo obj = new Demo();
23 obj.setValue(5,6);
24 obj.showValue();
25 }
26}
1class Other{
2 public double num;
3 public Other(int num){
4 this.num = num;
5 System.out.println(num);
6 //print 5 to the console
7 }
8}
9
10class scratch{
11 public static void main(String[] args) {
12 Other method = new Other(5);
13 System.out.println(method.num);
14 //prints 5.0 to the console
15 }
16}
1// this keyword in java example
2import java.util.*;
3class Demo
4{
5 // instance variable
6 int m;
7 int n;
8 public void setValue(int m, int n)
9 {
10 m = m;
11 n = n;
12 }
13 public void showValue()
14 {
15 System.out.println("Value m = " + m);
16 System.out.println("Value n = " + n);
17 }
18}
19public class ThisKeywordDemo
20{
21 public static void main(String[] args)
22 {
23 Demo obj = new Demo();
24 obj.setValue(5, 6);
25 obj.showValue();
26 }
27}