Laura
0
Q:

java this keyword

// this keyword in java example
import java.util.*;
class Demo
{
   // instance variable
   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();
   }
}
1
// java program using ‘this’ keyword
class Demo
{
   int m;
   int n;
   public void setValue(int m, int n)
   {
      // java this keyword
      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();
   }
}
1
class Other{
    public double num;
    public Other(int num){
        this.num = num;
        System.out.println(num);
      	//print 5 to the console
    }
}

class scratch{
    public static void main(String[] args) {
        Other method = new Other(5);
        System.out.println(method.num);
      	//prints 5.0 to the console
    }
}
1
//Java code for using 'this' keyword to 
//refer current class instance variables 

//code taken from www.geeksforgeeks.org but has been edited

class Test 
{ 
    int a; 
    int b; 
      
    // Parameterized constructor 
    Test(int a, int b) 
    { 
        //this helps differentiate between members of class and parameters
        this.a = a; 
        this.b = b; 
    } 
} 
2
class Demo
{
   // instance variable
   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();
   }
}
0

New to Communities?

Join the community