File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes this keyword usage Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Soft Skills this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "this keyword usage" Watch "this keyword usage" New topic
Author

this keyword usage

Rama Lakshmi
Greenhorn

Joined: Mar 31, 2006
Posts: 27
Hi,

can any one pls exaplain that why can't i use this keyword in static block?

and pls explain me the flow of excution...

public class fun4 {

int b;
int k;
{
b=9;
System.out.println("Instance block started");

}
static{
//this.k=90; //getting compilation error
System.out.println("Static block started");
}


public static void main(String[] args) {

fun4 f = new fun4();

System.out.println("Main method started");


}


}

--Thanks in Advance
Rama
Leandro Melo
Ranch Hand

Joined: Mar 27, 2004
Posts: 401
Hi ramasri.

You cannot use this inside a static block because this relates to an instance of a class ("this instance"), while static blocks belong to the class itself. So, which one is the this instance when you're inside a block that does not belong specifically to any instance? In the case of your program, the static block is execute when the class is loaded, that's why the first output you see is "Static block started". Then, instace data is initialized. Is that clear?


Leandro Melo
SCJP 1.4, SCWCD 1.4
Rama Lakshmi
Greenhorn

Joined: Mar 31, 2006
Posts: 27
Hi Leandro

Thank you for quick reply..

Yes it's cleared now

--Ramasri
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: this keyword usage