Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Bad Java Rule Round-up question (#235)

 
steve hitch
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Question 235, as stated, is not correct. It reads:
(#235) TRUE or FALSE: a static inner class (considered a
top-level nested class) can NOT access non-static variables
of the outer class.
The desired answer is TRUE, but in practice, is false.
The following code shows how, with Outer being the outer
class, three being the non-static variable, and Inner
being the static inner class:
public class Outer {
protected static Outer self = null;
protected int three = 3;
public Outer() {
self = this;
Inner.doIt();
}
protected static class Inner {
protected static void doIt() {
if (Outer.self != null) {
System.out.println(Outer.self.three);
}
}
}
}
 
Jim Yingst
Wanderer
Sheriff
Posts: 18671
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You are correct Steve. I think the intended meaning of the question would be clearer with this wording:
(#235) TRUE or FALSE: a static inner class (considered a
top-level nested class) can NOT access non-static variables
of the outer class without using an explicit reference to an instance of the outer class.
(TRUE)
Of course, that makes it longer ... Maybe it would be easier to ask instead the converse:
TRUE or FALSE: a non-static inner class can access non-static variables of the outer class without using an explicit reference to an instance of the outer class.
(TRUE)
 
paul wheaton
Trailboss
Pie
Posts: 21385
Firefox Browser IntelliJ IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This was once discussed before: http://www.javaranch.com/ubb/Forum24/HTML/001339.html
Although nothing came of it. I suggested that the question be rewritten as
<pre>
public class Outer
{
int x ;
static class Inner
{
void foo()
{
x = 5 ;
}
}
}
</pre>
Then the answers could be "compiles". "Does not compile".
What do you think?
 
Jim Yingst
Wanderer
Sheriff
Posts: 18671
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Works for me.
 
steve hitch
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Agree completely!
 
Brusk Baran
Ranch Hand
Posts: 132
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Using j2sdk1-4-0
and DOES NOT COMPILE..
AND MUST NOT COMPILE..
In 2000, compilers were behaving strange then!!! javascript: x()
Eek!
 
Marilyn de Queiroz
Sheriff
Posts: 9059
12
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hard to format this code in a text file.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic