wood burning stoves 2.0*
The moose likes Beginning Java and the fly likes Inner classes Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Inner classes " Watch "Inner classes " New topic
Author

Inner classes

Paul Mrozik
Ranch Hand

Joined: Feb 10, 2013
Posts: 117

This is from Bruce Eckel's TIJ book, please tell me whether I've done it correctly.

ch 8/p 12:

Create an interface with at least one method, in its own package. Create a class in a separate package. Add a protected inner class that implements the interface. In a third package, inherit from your class and, inside a method, return an object of the protected inner class, upcasting to the interface during the return.


So here's the interface:



And the separate class, note the different package:



And finally, the last extended class:



The problem I came across here was that even though Automobile extends Vehicle, it couldn't access the protected inner class - probably because Vehicle is in a totally different package. To get around this, I created a public method in Vehicle which returns an object of the inner class (Tire). In Automobile, the getInflatableObject() method then upcasts the Vehicle.Tire object as the instructions ask.

So is this the right way to do it? Any other comments? The only place I've come across interfaces & inner classes is in the Swing GUI, so I'm not really sure how all this might be used in real life.

Oh, and why do I have to import inflate again in the Automobile class since it's already been imported in Vehicle?

Thanks in advance.

Sresh Rangi
Ranch Hand

Joined: Nov 28, 2012
Posts: 47
    
    2
There's a few compile errors in the posted code. Inside the Vehicle.Tire class, the inflate and toString methods need to be public, and toString needs to return a value.

The Automobile class can access the protected inner class, but not the constructor because it defaults to being protected (same as the class). The constructor would be visible to subclasses of the inner class, but not subclasses of Vehicle. If you add a public constructor to the inner class, you can then create an instance of it directly in the Automobile class.

Imports are used to resolve names within a single file, and are not inherited in any way, so each file needs to repeat any imports it uses.
Paul Mrozik
Ranch Hand

Joined: Feb 10, 2013
Posts: 117

Thanks a lot for clearing that up, Sresh. I posted just before going to bed, so I admit I did not compile. I did write a similar set of classes earlier which did compile, but made no logical sense (Driveable, Bike, Vehicle) so I thought I'd rewrite everything quickly.



 
It is sorta covered in the JavaRanch Style Guide.
 
subject: Inner classes