• 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
  • Paul Clapham
  • Ron McLeod
  • Liutauras Vilda
  • Bear Bibeault
Sheriffs:
  • Jeanne Boyarsky
  • Tim Cooke
  • Devaka Cooray
Saloon Keepers:
  • Tim Moores
  • Tim Holloway
  • Piet Souris
  • salvin francis
  • Stephan van Hulst
Bartenders:
  • Frits Walraven
  • Carey Brown
  • Jj Roberts

Doubt in S&B book - Inner classes

 
Greenhorn
Posts: 17
  • 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());
}
}

 
Ranch Hand
Posts: 329
Oracle Java Linux
  • 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
  • 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.
 
Consider Paul's rocket mass heater.
reply
    Bookmark Topic Watch Topic
  • New Topic