Tuesday 23 January 2018

this Keyword In Java


this  keyword is  a reference variable  that refers to the current object.

Uses

It can be used to refer instance variable of current class.

It can be used to call current class constructor.

It can be used to call current class method.

Example 1:
Using this keyword


class Add{ 
int a,b; 

Add(int a,int b){ 
this.a=a; 
this.b=b; 

void display()
{
    System.out.println("sum is:"+(a+b));
}
public class Result {

  
    public static void main(String[] args) {
       Add a1=new Add(67,78); 
       a1.display();
   }
   
}
Output:
sum is: 145

Example 2:
Without using this keyword

class Add{ 
int a,b; 

Add(int a,int b)
a=a; 
b=b; 

void display()
{
    System.out.println("sum is:"+(a+b));
}
public class Result {

  public static void main(String[] args) {
       Add a1=new Add(67,78); 
       a1.display();
     }
   }

Output:
sum is:0

Example 3:
Where this keyword is not required


class Add{ 
int a,b; 
Add(int c,int d){ 
a=c; 
b=d; 

void display()
{
    System.out.println("sum is:"+(a+b));
}

public class Result {

  public static void main(String[] args) {
       Add a1=new Add(67,78); 
       a1.display();
   
    }
   
}
Output:
sum is: 145


No comments:

Post a Comment

apply function in R

1) apply function: It takes 3 arguments matrix,margin and function.. Example: m<-matrix(c(1,2,3,4),nrow=2,ncol=2) m #1 indicates it is ap...