This post originated from an RSS feed registered with Java Buzz
by instanceof java.
Original Post: Java programming interview questions on this keyword part 3
Feed Title: Instance Of Java
Feed URL: http://feeds.feedburner.com/blogspot/TXghwE
Feed Description: Instance of Java. A place where you can learn java in simple way each and every topic covered with many points and sample programs.
Let us see remaining java programs on this keyword
Java Quiz on this keyword part #3
Program #9: Is it possible to Pass this as parameter of a method?
package thiskeywordinterviewprograms.java;
public class ThisDemo {
int a,b;
public ThisDemo Show(){
this.a=10;
this.b=20;
return this;
}
public static void main(String[] args) {
ThisDemo obj = new ThisDemo();
System.out.println("a="+obj.a);
System.out.println("b="+obj.b);
ThisDemo obj1 = obj.Show();
System.out.println("a="+obj1.a);
System.out.println("b="+obj1.b);
}
}
Click for Output
a=0
b=0
a=10
b=20
Yes we can pass this as the return type of the method.
As "this" also points to current class object we can always return this as return type of the method.
if we return this as return type the return type of the method should be class name because this always points to current class object.
Result will be current class object and we can do all stuff as we are doing with object.
Program #10: Is is possible to access static variables and static methods using this keyword?
Click for Output
a=0
b=0
a=10
b=20
Yes we can refer static members using this keyword. But it is not best practice to use this to access static variables and static methods.
Program #11:Java program to test whether we can use this in static block or not?
package thiskeywordinterviewprograms.java;
public class ThisDemo {
static int a,b;
static{
this.a=10;
this.b=20;
}
public static void main(String[] args) {
ThisDemo obj = new ThisDemo();
System.out.println("a="+obj.a);
System.out.println("b="+obj.b);
}
}
Click for Output
We can not use this in static block because static blocks executed in class loading time itself at that time object will not be created and this refers to null so we can not use this in static block leads to compile time error.
Program #12: Java interview program to test whether we can use this in static methods?
package thiskeywordinterviewprograms.java;
public class ThisDemo {
static int a,b;
public static void main(String[] args) {
ThisDemo obj = new ThisDemo();
this.a=10;
this.b=20;
System.out.println("a="+obj.a);
System.out.println("b="+obj.b);
}
}
Click for Output
Compile time error: can not use this in static content