Nesting Java Inner Classes

How can I create an instance of class C if it is nested in class B and class B is nested in class A again?

class A { class B { class C { .............. } } } 
+4
source share
4 answers

To create an instance of C , you will need the enclosed instance of B , which in turn will have a private instance of A

 A someA = new A(); B someB = a.new B(); C someC = b.new C(); 
+3
source

Something like this should do it

 ABC c = new A().new B().new C(); 

You can combine new () lines if you wish.

+2
source

You can create such an instance.

 A a = new A(); AB b = a.new B(); ABC c = b.new C(); 

It works.

 public class InnerClassTest1 { public static void main(String[] args) { A a = new A(); AB b = a.new B(); ABC c = b.new C(); c.setValue(100); System.out.println("Innermost value " + c.getValue()); } } class A { class B { class C { int value; public int getValue() { return value; } public void setValue(int value) { this.value = value; } } } } 
+1
source

If classes do not functionally rely on nested classes, that is, class C does not refer to the methods and / or fields of class B or class A , then you can make static classes.

 class A { static class B { static class C { ... } } } 

You can create them from anywhere, wherever you are:

 ABC c = new ABC (); 
0
source

Source: https://habr.com/ru/post/1435206/


All Articles