Win a copy of Clojure in Action this week in the Clojure forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Doubt in S&B book - Inner classes

 
Adam Schweitzer
Greenhorn
Posts: 17
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ref. page 642
From outside the outer class instance code (including static method code
within the outer class)
, the inner class name must now include the outer
class's name:
MyOuter.MyInner
(emphasis mine)

However, this doesn't seem to be accurate. For instance, this code compiles and runs (under a 1.4 compiler, albeit, as I don't have access to a 1.5 one currently):

class MyOuter {
class MyInner {
private int x = 5;
int getX() { return x; }
}

public static void main(String [] args) {
MyOuter out = new MyOuter();
MyInner m = out.new MyInner(); // not MyOuter.MyInner

System.out.println(m.getX());
}
}
 
Sergio Tridente
Ranch Hand
Posts: 329
Java Linux Oracle
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It compiles fine under java 1.5.

The only problem would come when trying to create an instance of the inner class: you'll need to explicitly use an instance of the outer class.

The following: MyInner m = new MyInner()

- Will work inside a non static method. It is interpreted as: MyInner m = this.new MyInner()
- Will not work in a static context.
 
Adam Schweitzer
Greenhorn
Posts: 17
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Sergio Tridente:
It compiles fine under java 1.5.

The only problem would come when trying to create an instance of the inner class: you'll need to explicitly use an instance of the outer class.

The following: MyInner m = new MyInner()

- Will work inside a non static method. It is interpreted as: MyInner m = this.new MyInner()
- Will not work in a static context.

Yup, that's all true..

It just seemed odd to me that the book said static methods in the same class as the inner class had to use the MyOuter.MyInner syntax, because MyInner should still be in the symbol table (or Javac's equivalent) and hence visible to the static method.

I believe this is an error in the book, and it's not in the "errata" post.
 
I agree. Here's the link: http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic