Creating instances of public classes in public classes

So I have something like the following:

public class Enclosing<T extends Comparable<T>> { // non-relevant code snipped public class Inner { private T value; public Inner(T t) { value = t; } } } 

Everything compiles and the world is happy. However, when I try to create an instance of Enclosing.Inner as follows, I cannot:

 new Enclosing<Integer>.Inner(5); 

The following error has occurred:

Cannot assign element type Enclosing<Integer>.Inner using a parameterized connection name; use its simple name and the attached instance of type Enclosing<Integer> .

It is important to note that I cannot make the inner class static because it contains a field of type T

How can I get around this?

+4
source share
2 answers

To create an instance of an inner class , you must first create an instance of the outer class. Then create an internal object inside the external object using this syntax:

  Enclosing<Integer> outerObject = new Enclosing<Integer>(); Enclosing<Integer>.Inner innerObject = outerObject.new Inner(); 

Ugly syntax suggests the smell of code in this design. There should probably be some kind of factory method in the Enclosing class ( getInner or something), and the inner class should probably implement a public interface if used from outside its surrounding class.

+10
source

just ran into the same problem, solved it as follows in java7

 public class Test { static class A<T> { public class B { } } A<String> a = new A(); class C extends AB { C() { Test.this.a.super(); } } public void test() { C c = new C(); AB b = this.a.new B(); } } 
0
source

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


All Articles