File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Beginning Java and the fly likes clarify this keyword used in my java program Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Java Interview Guide this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "clarify this keyword used in my java program" Watch "clarify this keyword used in my java program" New topic

clarify this keyword used in my java program

venkateswarlu keesara

Joined: Sep 17, 2004
Posts: 3
public class Test {
public static void test() {
public static void print() {
public static void main ( String args[]) {
ans:compilation error:
non static "this" variable can not be refernced from static method
Eric Pascarello

Joined: Nov 08, 2001
Posts: 15385
This forum is meant for issues with the JavaRanch forum itself. I will have someone move it to the correct forum: Java Beg.

Dirk Schreckmann

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

Joined: Oct 02, 2003
Posts: 11957

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???

There are only two hard things in computer science: cache invalidation, naming things, and off-by-one errors
I agree. Here's the link:
subject: clarify this keyword used in my java program
It's not a secret anymore!