Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why should I use nested classes? [closed]

When is it feasible to nest classes? The most common advantage of it that I see is "shared scope" (use of variables across classes).

Is this less attractive/less a best practice than just putting the nested class in it's own file, and passing the arguments through the Constructor?

like image 837
Dane Balia Avatar asked Jan 21 '13 11:01

Dane Balia


People also ask

When should I use nested classes?

Nested class: Use it if your requirements are similar to those of a local class, you want to make the type more widely available, and you don't require access to local variables or method parameters.

What is the point of nested classes in Java?

In Java, it is also possible to nest classes (a class within a class). The purpose of nested classes is to group classes that belong together, which makes your code more readable and maintainable.

Why do we need nested classes in C#?

In C#, a user is allowed to define a class within another class. Such types of classes are known as nested class. This feature enables the user to logically group classes that are only used in one place, thus this increases the use of encapsulation, and create more readable and maintainable code.

Why do we need inner classes in Java?

Inner classes are a security mechanism in Java. We know a class cannot be associated with the access modifier private, but if we have the class as a member of other class, then the inner class can be made private. And this is also used to access the private members of a class.


2 Answers

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

  1. It is a way of logically grouping classes that are only used in one place.

  2. It increases encapsulation.

  3. Nested classes can lead to more readable and maintainable code.

  4. Child to parent class connection is simpler as it visually illustrates the variables and methods of each class.

like image 71
dd619 Avatar answered Sep 22 '22 22:09

dd619


In addition to those mentioned already, one other benefit is:

  • Nested classes also help you achieve multiple implementation inheritance (ref: Thinking in Java, page 369 - section "Why inner classes"?). As far I know, there is no other way to achieve it in Java.
like image 29
Dheeru Mundluru Avatar answered Sep 22 '22 22:09

Dheeru Mundluru