• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

variable this is undefined ?

 
Pankaja Shinde
Ranch Hand
Posts: 87
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Consider the following class:

public class Test
{
public static void test()
{
this.print();
}
public static void print()
{
System.out.println("Test");
}
public static void main(String args [])
{
test();
}
}

What is the result of compiling and running this class?

A. The string Test is printed to the standard out.
B. A runtime exception is raised stating that an object has not been created.
C. Nothing is printed to the standard output.
D. An exception is raised stating that the method test cannot be found.
E. An exception is raised stating that the variable this can only be used within an instance.
F. The class fails to compile stating that the variable this is undefined.

Correct Answer : Option F

Why ?

Pankaj Shinde
 
Pandharinath Barve
Greenhorn
Posts: 13
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
you can not use "this" in static context.

Regards,
Pandharianth.
 
anil kumar
Ranch Hand
Posts: 447
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi

In static method there is no access to the keyword this or super.
 
Bijendra S. Rajput
Ranch Hand
Posts: 41
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Pankaja,

Yes, the ans of this question is F. This will fail at compile time.
The reason is that print() is a static method and when we are calling this method inside test() method, we are using this which is totally wrong. With static methods we can not use this keyword, static methods belongs to class. So this program will not compile.

if you can modify, like this

public static void test(){
print();

}


then this program will run and output will be "Test".
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic