permaculture playing cards
The moose likes Java in General and the fly likes this Refrence Problem Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of REST with Spring (video course) this week in the Spring forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "this Refrence Problem" Watch "this Refrence Problem" New topic

this Refrence Problem

Vipin Raturi

Joined: Dec 28, 2006
Posts: 1
hi all,
i am new member in your javaranch family and scjp preperation as well as.
i have problem with below code. please check it.

class vipin{
public static void main(String[] arg){
System.out.println("Class Name is"+this.getClass().getName());

It shows some problem on compilation. but if, i make an object of vipin class and do it like.

class vipin{
public static void main(String[] arg){
vipin obj=new vipin();
System.out.println("Class Name is"+ obj.getClass().getName());

now,It gives name of class. as, i expected.
So, what is the problem with this refrence. i m using jdk1.4
Please, anybody reply this problem.
Anu Pillai

Joined: Oct 09, 2006
Posts: 28
Its giving an error because the keyword 'this' cannot be used in a static method. Give that statement in another method and call this method from main, it will work.
fred Joly
Ranch Hand

Joined: Jan 19, 2006
Posts: 55
You can not use "this" in "main wich is a static method
because "this" refers to an object and a static method
can only refer to a class (not an instanciation)
Ramna Reddy
Ranch Hand

Joined: Aug 06, 2006
Posts: 96
"this" and "super" can not be used in static blocks & methods.
I agree. Here's the link:
subject: this Refrence Problem
jQuery in Action, 3rd edition