• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

this Refrence Problem

 
Vipin Raturi
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Greenhorn
Posts: 28
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 55
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 96
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
"this" and "super" can not be used in static blocks & methods.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic