• 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

variable this is undefined ?

 
Ranch Hand
Posts: 87
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
 
Greenhorn
Posts: 13
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
you can not use "this" in static context.

Regards,
Pandharianth.
 
Ranch Hand
Posts: 447
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi

In static method there is no access to the keyword this or super.
 
Ranch Hand
Posts: 41
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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".
 
reply
    Bookmark Topic Watch Topic
  • New Topic