• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Liutauras Vilda
  • Tim Cooke
  • Jeanne Boyarsky
  • Paul Clapham
Sheriffs:
  • Devaka Cooray
  • Ron McLeod
  • paul wheaton
Saloon Keepers:
  • Tim Moores
  • Piet Souris
  • Tim Holloway
  • Stephan van Hulst
  • Carey Brown
Bartenders:
  • Al Hobbs
  • Frits Walraven
  • Scott Selikoff

this keyword usage

 
Greenhorn
Posts: 27
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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
 
Ranch Hand
Posts: 401
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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?
 
Rama Lakshmi
Greenhorn
Posts: 27
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi Leandro

Thank you for quick reply..

Yes it's cleared now

--Ramasri
 
The fastest and most reliable components of any system are those that are not there. Tiny ad:
the value of filler advertising in 2021
https://coderanch.com/t/730886/filler-advertising
reply
    Bookmark Topic Watch Topic
  • New Topic