Home | | Sitemap ||Page number :11

Use of “this” keyword

The “this” keyword refers to the object by which a method was called. Have a look at this piece of class.

// This is a wrong code… class no_this { int a,b;

void take(int a,int b) { a=a; b=b; } The mistake in this program can be easily pointed out. We cannot use the same name for the instance variables and the variables which are declared as parameters. The reason being the instance variables are hidden when we use parameters with the same name. If we are determined to use the same name, then the “this” keyword comes to rescue. Now look at a class named “with_this

class with_this {

int n,n2; int sm; public void get(int n,int n2) { this.n=n; this.n2=n2; }

public void sum() { sm=n+n2; System.out.println("Sum is "+sm); }

}

class apply9 { public static void main(String args[]) { with_this obj=new with_this(); obj.get(10,12); obj.sum(); } }

We can use the “this” keyword even if we have used different names for the parameters and the instance variable.

Exercise –

Q1. What is the importance of class in Java?

Q2. What is the role of “main” method in the execution of programs?

Q3. Explain the two uses of dot operator.

Q4. Why is the main method preceded by the keyword static?

Q5. A method can be written even without using a return type. What is the benefit if we use them?

Q6. Explain method overloading and demonstrate it with the help of an example.

Q7. State the difference between “pass by value” and “pass by reference”.

Q8. State the use of ‘this’ keyword.

Q9. Explain recursion with the help of an example.

Q10.Write about pure and impure function.