File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Beginning Java and the fly likes When to use inner class? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "When to use inner class?" Watch "When to use inner class?" New topic
Author

When to use inner class?

abalfazl hossein
Ranch Hand

Joined: Sep 06, 2007
Posts: 635
I want to know where inner classes are useful?
Lucky J Verma
Ranch Hand

Joined: Apr 11, 2007
Posts: 278


Inner class is defined inside a class as name suggests.
So it might be used to define some new datatype used by any method or anything inside the class and won'nt have to be used outside the class.just like methods and variables inside a class.

I will give you an example -

Inside a class - in a method , i am doing some sorting like Collections.sort() and i need to define my comparator for me which wont be used outside that class.
So before doing sort() i define a class implementing comparator interface and used in comparator .
This inner class wont be visible outside outer class.

Class Outer{

Class myComparator implements Comparator{}

void someMethod(List a){

Collections.sort(a, new myComparator());}




}

Check out this link.It might be helpful.
http://download.oracle.com/javase/tutorial/java/javaOO/innerclasses.html
Jesper de Jong
Java Cowboy
Saloon Keeper

Joined: Aug 16, 2005
Posts: 14074
    
  16

Lucky, to make the inner class really invisible outside the enclosing class, you'll have the make it private. And if it doesn't need to access member variables or non-static methods from the enclosing class, it's also a good idea to make it static. Like this:


Java Beginners FAQ - JavaRanch SCJP FAQ - The Java Tutorial - Java SE 7 API documentation
Scala Notes - My blog about Scala
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: When to use inner class?
 
Similar Threads
What is a class file with $ symbol in the name
werid output for For loop
static inner class instantiation
Inner Classes
Inner Classes