aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Doubt in S&B book - Inner classes Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Doubt in S&B book - Inner classes" Watch "Doubt in S&B book - Inner classes" New topic
Author

Doubt in S&B book - Inner classes

Adam Schweitzer
Greenhorn

Joined: May 26, 2006
Posts: 17
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

Joined: Mar 22, 2007
Posts: 329

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.


SCJP 1.4 (88%) - SCJP 5.0 Upgrade (93%) - SCWCD 1.4 (97%) - SCBCD 5.0 (98%)
Adam Schweitzer
Greenhorn

Joined: May 26, 2006
Posts: 17
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
 
subject: Doubt in S&B book - Inner classes