This week's giveaway is in the EJB and other Java EE Technologies forum.
We're giving away four copies of EJB 3 in Action and have Debu Panda, Reza Rahman, Ryan Cuprak, and Michael Remijan on-line!
See this thread for details.
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 EJB 3 in Action this week in the EJB and other Java EE Technologies 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
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: 15376
    
    6
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: 10916
    
  12

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
 
wood burning stoves
 
subject: clarify this keyword used in my java program
 
Similar Threads
clarify this keyword used in my java program
[this]....
overloading
Forgetting about constructors
Object of Class N declared inside Class N itself.