Suppose I have class А and inner class А.В А , and I create an object of class А.В А in a method of another class (not А ).

 A obj1 = new A(); AB obj2 = obj1.new B(); 

What is an obj2 object? Is it part of obj1 or an independent independent object?

I mean, the essence of a single object is something single, for example, an instance of Apple , which contains member data, a сорт and a member function to упастьСВетки() . What is the meaning of the inner class in the same way? Is it possible to give a similar example for inner classes?

  • What exactly are you interested in? obj2 is a separate object in memory, but with access to fields and methods of the outer class. - Nofate
  • and a pointer to an external class that is stored inside it, so without creating an external class, you cannot create an internal class. Therefore, the answer to your question, rather part of obj1 than an independent object. - pavel
  • I mean, for what purpose would you use the inner class? - luckystrrrike
  • use, if it belongs to the same object and is almost never used anywhere. Apple has a variety. varieties can be declared inside the class. Weight can be separately, so we can apply weight to Pears - Senior Pomidor
  • I use for convenience purposes. If a class must see the fields of the outer class and it is short, then it is convenient to put the source code directly into the outer class. And so the files .java to hell and more is obtained. - Sergey

1 answer 1

They are needed in order to have a link to the external class in which they were nested. Sometimes objects of some classes themselves have little value without binding it to some element.

I will give a commonplace example, be careful, it is somewhat stretched. We have a parent, he has children. To get the full name of the child, you must have a link to the parent. And here there are several options: use the field explicitly with reference to the parent, or use the functions of the language (inner class).

 class Parent { private String name; public Child createChild(String name) { return new Child(name); } public class Child { private String name; private Child(String name) { this.name = name; } public String getFullName() { return name + " " + Parent.this.name; } } }