Home java Why in java need nested classes?

Why in java need nested classes?




Why in java need nested classes?

Answer 1, Authority 100%

First you need to understand the difference between a non-static nested classes (non static nested classes) and static nested classes (static nested classes).

Non-static nested classes (non static nested classes)

They – inner classes


Where to apply?

Where you describe the structure of the future facility, which has not only the state and behavior, but also has some additional (composite) parts. Without which the object would not exist alone.

For example, a car. The meaning of it is lost, if it stands in the courtyard on the bricks, and the wheels of it lie in the garage, but you need to sit down and go. In this case, you have to spend time to take the car, take the jack, take the wheel and do all the steps to install them.

How to use?

The inner class has access to all of the methods of the fields and methods of the outer class, and can refer to them directly. But the external class can access methods and fields of the internal reference only. It looks like this:

public class Outer {
  Public Static Void Main (String [] Args) {
    Outer outer = new Outer ();
    outer.print ();
  private int outer_x = 100;
  void print () {
    Inner inner = new Inner ();
    inner.innerMethod ();
  class Inner {
    public void innerMethod () {
      System.out.println (outer_x);

Or to the method of main call directly the internal class method, we can do so:

Public Static Void Main (String [] Args) {
  Outer outer = new Outer ();
  Outer.Inner inner = outer.new Inner ();
  inner.print ();

The inner class can also be defined within the methods and cycles.

Static nested classes (static nested classes)

The first thing to realize is that nested classes, unlike the domestic marked keyword static . And that in a nested class can work with the methods and fields of the outer class, they must also be labeled static .

Where to apply?

Well, take for example a situation where Peter goes to school with his briefcase, and Masha without, ie, carries textbooks in hands. Then Peter can say – “Look, I can share your portfolio, you have luggage it their books, I still carry it …”. That is Masha put her books to list Petit, because Peter is not greedy, he will share.

How to use?

All access to the fields and methods of the outer class, and contrary to the fields and methods of a nested class is through the class.

public class Outer {
  Public Static Void Main (String [] Args) {
    Outer outer = new Outer ();
    outer.print ();
    // or
    Outer.Inner.innerMethod ();
  private static int outer_x = 100;
  public void print () {
    Inner.innerMethod ();
  static class Inner {
    private static void innerMethod () {
      System.out.println (Outer.outer_x);

Answer 2

I will try to explain as simply:

In general, in the java inner classes serve us to tie one entity to another. For example: the essence of CAR , it has wheel , transmission , pedal . And why create a public class with all this? Just thrown in as an inner class of car and here Lafayette.

It is also convenient for the use of any type of Paterno singleton and builder .

Answer 3

The internal class is usually inherited from class or implements the interface, and the code of the internal class manipulates the external class object in which it was created. So it can be said that the internal class is something like the “windows” in the external class.

Natural question arises: “If I need a link to the interface, why not implement this interface to the external class?” The answer here is: “If all that you need is, it should be done.” But what distinguishes the internal class implementing the interface, from an external class that implements the same interface? It is not always possible to use the convenience of interfaces – the encore has to work with the implementation. Therefore, the most good reason for the use of internal classes is formulated as follows:

Each internal class is able to independently inherit a certain implementation. Thus, the internal class is not limited when inherited in situations where the external class is already inherited.

Without the ability of internal classes to inherit (in fact), the implementation of more than one specific or abstract class Some tasks of planning and programming would have an extremely difficult solution. Therefore, the inner class acts as “incursions” of multiple inheritance. Interfaces take part of this task, while internal classes actually provide “multiple implementing inheritance”. That is, the internal classes allow you to inherit from several “non-interfaces.”

To understand what is said, consider the situation where two interfaces in one way or another should be implemented in the class. Due to the flexibility of the interfaces, you have two options: a single class or internal class:

//: innerclasses / multiinterter * faces.java
// two ways to implement multiple interfaces
// in one class.
Interface A {}
Interface in {}
Class Y Implements A {
 In Makeb () {
   // Anonymous internal class:
  RETURN NEW B () {};
Public Class MultiInterfaces {
 Static Void Takesa (A) {}
 Static Void Takesb (B B) {}
 Public Static Void Main (String [] Args) {
  X x = new x ();
  Y y = new y ();
  Takesa (x);
  Takesb (x);
  Takesb (y.makeb ());
} ///: ~

Of course, the choice of this or that method of organizing the code depends on the specific situation. However, the task you, the challenge itself, should suggest that for it before: one separate class or internal class. But in the absence of other restrictions, both approaches used in the considered example are not derived from the point of view of implementation. Both are working.
However, if instead of the interfaces you have specific or abstract classes, the internal classes will have to “call” if the new class is somewhat for acting the functionality of the other two classes:

//: innerclasses / multiimplementation.java
// When using specific or abstract classes
// Internal classes provide the only way
// Conduct the "multiple inheritance of implementation."
Package Innerclasses;
Class D {}
Abstract Class E {}
Class Z Extends D {
  E Makee () {Return New E () {};}
Public Class Multiimplementation {
 Static Void Takese (E E) {}
 Public Static Void Main (String [] Args) {
  Z z = new z ();
  Takese (z.makee ());
} ///: ~

If you do not have to solve the task of the “multiple inheritance of implementation”, most likely you can write any program without using the features of the internal classes. On the other hand, internal classes open the following additional features.

  1. Internal class can exist an arbitrary number of instances, each of which contains its own information that does not depend on the state of the external class object.

  2. One exterior class may contain several internal classes that are differently implemented by one interface or inherit from the only basic class. An example of such a design will soon be considered.

  3. The place of creation of the object of the inner class is not tied to the place and time of the creation of the object of the outer class.

  4. The inner class does not create a “is it” class relationship that could cause confusion; it is a separate entity.

Bruce Eckel “The JAVA Philosophy”

Programmers, Start Your Engines!

Why spend time searching for the correct question and then entering your answer when you can find it in a second? That's what CompuTicket is all about! Here you'll find thousands of questions and answers from hundreds of computer languages.

Recent questions