this in java code example
Example 1: this obj java meaning
public class Point {
public int x = 0;
public int y = 0;
public Point(int x, int y) {
this.x = x;
this.y = y;
}
}
Example 2: how to use the this keyword in java
class Other{
public double num;
public Other(int num){
this.num = num;
System.out.println(num);
}
}
class scratch{
public static void main(String[] args) {
Other method = new Other(5);
System.out.println(method.num);
}
}
Example 3: this keyword in java
class Demo
{
int m;
int n;
public void setValue(int m, int n)
{
this.m = m;
this.n = n;
}
public void showValue()
{
System.out.println("Value m = " + m);
System.out.println("Value n = " + n);
}
}
public class ThisExample
{
public static void main(String[] args)
{
Demo obj = new Demo();
obj.setValue(5,6);
obj.showValue();
}
}
Example 4: this keyword in java
import java.util.*;
class Demo
{
int m;
int n;
public void setValue(int m, int n)
{
m = m;
n = n;
}
public void showValue()
{
System.out.println("Value m = " + m);
System.out.println("Value n = " + n);
}
}
public class ThisKeywordDemo
{
public static void main(String[] args)
{
Demo obj = new Demo();
obj.setValue(5, 6);
obj.showValue();
}
}
Example 5: this in java
this() : used for calling the constructor .
we can only use it in the constructor
this. : used for calling the instance variables
we can use in any object instances