• 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 Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Tim Cooke
  • Devaka Cooray
  • Ron McLeod
  • Jeanne Boyarsky
Sheriffs:
  • Liutauras Vilda
  • paul wheaton
  • Junilu Lacar
Saloon Keepers:
  • Tim Moores
  • Stephan van Hulst
  • Piet Souris
  • Carey Brown
  • Tim Holloway
Bartenders:
  • Martijn Verburg
  • Frits Walraven
  • Himai Minh

When to use inner class?

 
Ranch Hand
Posts: 635
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I want to know where inner classes are useful?
 
Ranch Hand
Posts: 278
  • Likes 2
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator


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
 
Java Cowboy
Posts: 16084
88
Android Scala IntelliJ IDE Spring Java
  • Likes 2
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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:
 
I think I'll just lie down here for a second. And ponder this tiny ad:
the value of filler advertising in 2021
https://coderanch.com/t/730886/filler-advertising
reply
    Bookmark Topic Watch Topic
  • New Topic