Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

clarify this keyword used in my java program

 
venkateswarlu keesara
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
public class Test {
public static void test() {
this.print();
}
public static void print() {
System.out.println(�Test�);
}
public static void main ( String args[]) {
test();
}
}
ans:compilation error:
non static "this" variable can not be refernced from static method
 
Eric Pascarello
author
Rancher
Posts: 15385
6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This forum is meant for issues with the JavaRanch forum itself. I will have someone move it to the correct forum: Java Beg.

Eric
 
Dirk Schreckmann
Sheriff
Posts: 7023
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Moving this to the Java in General (beginner) forum...
 
David Ulicny
Ranch Hand
Posts: 724
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
static methods couldn't use this because they could be called without any instance of the class.
 
fred rosenberger
lowercase baba
Bartender
Pie
Posts: 12097
30
Chrome Java Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The keyword "this" is used to refer to the current object. You're telling an object to run the <whatever> method on itself, instead of something else.

When you write a static method, you are saying "i don't need an object to call/run this method."

Hence, the problem. your saying "in this method that doesn't need an object, run a method on the current object". The Java Compiler is smart enough to know that this is gonna cause a problem - how to run a method on an object that doesn't necesarrily exist???
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic