| Author |
clarify this keyword used in my java program
|
venkateswarlu keesara
Greenhorn
Joined: Sep 17, 2004
Posts: 3
|
|
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
Joined: Nov 08, 2001
Posts: 15357
|
|
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
Joined: Dec 10, 2001
Posts: 7023
|
|
|
Moving this to the Java in General (beginner) forum...
|
[How To Ask Good Questions] [JavaRanch FAQ Wiki] [JavaRanch Radio]
|
 |
David Ulicny
Ranch Hand
Joined: Aug 04, 2004
Posts: 724
|
|
|
static methods couldn't use this because they could be called without any instance of the class.
|
SCJP<br />SCWCD <br />ICSD(286)<br />MCP 70-216
|
 |
fred rosenberger
lowercase baba
Bartender
Joined: Oct 02, 2003
Posts: 9944
|
|
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???
|
Never ascribe to malice that which can be adequately explained by stupidity.
|
 |
 |
|
|
subject: clarify this keyword used in my java program
|
|
|