• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Statics

 
Leonardo Go
Greenhorn
Posts: 13
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
//main is static right ???

public class Answers{

static class Caps {

void write(){
System.out.print("Lordan Go");
}
}

public static void main(String[] args){
Caps s = new Caps();
s.write();
}
}

/*
if i change the static to ... not static..

non-static variable this cannot be referenced from a static context
Caps s = new Caps();
*/

Please explain .. thnx
 
Mahesh Bhatt
Ranch Hand
Posts: 88
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
now thats an easy one .... look here ... u have made a class inside a class thats called a nested class ..... now see that u have declared this inner class as static ... right ... that means it is not associated with any object/reference ... it belongs to the class ....gottit ... now when it belongs to the class .... and not to any object ... how can u use "this" ...this refers to an object ...and the class doesn't belong to any object ...gottit ... even if u use "this" inside the main method ...u would get the same type of arror ... "this" points to an object ... and when u use "this" inside a static context ....the compiler says ..."man , what do u mean by this .... i am not with any object ... what do u mean by "this" ..."
 
Dirk Schreckmann
Sheriff
Posts: 7023
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Leonardo,

You might like to read the "Getting in Touch with your Inner Class" story in the JavaRanch Campfire Stories.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic