• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

clarify this keyword used in my java program

 
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
 
author
Posts: 15385
6
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
 
Sheriff
Posts: 7023
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Moving this to the Java in General (beginner) forum...
 
Ranch Hand
Posts: 724
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
static methods couldn't use this because they could be called without any instance of the class.
 
lowercase baba
Posts: 13091
67
Chrome Java Linux
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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???
 
reply
    Bookmark Topic Watch Topic
  • New Topic