Win a copy of Five Lines of Code this week in the OO, Patterns, UML and Refactoring forum!
  • 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 all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Bear Bibeault
  • Ron McLeod
  • Jeanne Boyarsky
  • Paul Clapham
Sheriffs:
  • Tim Cooke
  • Liutauras Vilda
  • Junilu Lacar
Saloon Keepers:
  • Tim Moores
  • Stephan van Hulst
  • Tim Holloway
  • fred rosenberger
  • salvin francis
Bartenders:
  • Piet Souris
  • Frits Walraven
  • Carey Brown

JQ Plus question

 
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Which statements can be placed at //1 without causing a compiler error.
public class Test {

int i1 ;
static int i2 ;
public void method1() {
int i;
// 1 Statement(s) to go here
}
}
It gives the following options
i = this.i1 ;
i = this.i2 ;
this = new Test() ;
this.i = 4 ;
this.i1 = i2 ;
The correct answers given are the first two and the last one.
What I cannot understand is why i = this.i2 ; is allowed because from reading Java books(Exam Prep, Cram etc)you cannot use this to refer to static members and vice versa.
The question is quite simple but the answer given has thrown me?
Any advice and suggestions would be appreciated.
p.s. GREAT SITE

[This message has been edited by John Paul (edited June 27, 2001).]
 
Sheriff
Posts: 15741
264
Mac Android IntelliJ IDE Eclipse IDE Spring Debian Java Ubuntu Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
What you can't do is use this in a static method. You can still use this in a non-static method to access a static class member, although this is confusing and a better way to do it would be to use the class name itself.
<pre>
class A {
static int x = 1;
static void bad() {
this.x = 5; // ILLEGAL - compile error!
}
void ok() {
this.x = 5; // allowed but confusing
A.x = 5; // same as above but not confusing
}
}
</pre>
 
John Paul
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks JUNILU
I see what you mean. Static methods may not use this to refer to variables, but non-static may use this to refer to a static variable....... am i right.
Any more examples will help sink it in my head.
 
    Bookmark Topic Watch Topic
  • New Topic