Except for GUIs, could anyone give me an example of why we need inner classes?

Recommended Answers

All 7 Replies

Hey zeroliken, long time no see! Remember the thread "Programming for..."? Well, this doubt is with regard to that thread. I am teaching my son Java. Now he can't understand the point of inner classes. Could you, kind of explain it in an easy manner?

Ask me if you want the book's pages which explain inner classes.

Thanks!

Yes long time no see :)

well an inner class is associated with an instance of its enclosing class and has direct access to that object's methods and fields

OK, so the inner classes gets access to private instance variables and methods of the outer class and vice - versa?

Can I scan the pages which he does not understand and show them to you so that you can explain?

I hope you can download!

I hope you can download!

the best explanation and reason for using inner classes/static inner classes is in the docs zeroliken gave you:
A nested class is a member of its enclosing class. Non-static nested classes (inner classes) have access to other members of the enclosing class, even if they are declared private. Static nested classes do not have access to other members of the enclosing class. As a member of the OuterClass, a nested class can be declared private, public, protected, or package private. (Recall that outer classes can only be declared public or package private.)

Why Use Nested Classes?

There are several compelling reasons for using nested classes, among them:

It is a way of logically grouping classes that are only used in one place.
It increases encapsulation.
Nested classes can lead to more readable and maintainable code.
Logical grouping of classes—If a class is useful to only one other class, then it is logical to embed it in that class and keep the two together. Nesting such "helper classes" makes their package more streamlined.

Increased encapsulation—Consider two top-level classes, A and B, where B needs access to members of A that would otherwise be declared private. By hiding class B within class A, A's members can be declared private and B can access them. In addition, B itself can be hidden from the outside world.

More readable, maintainable code—Nesting small classes within top-level classes places the code closer to where it is used.

commented: nice explanation :) +7
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.