Daniel
Daniel

Reputation: 855

Java nested nested class

I'm curious how (if?) nested nested classes are supposed to work.

Eclipse Oxygen.3 didn't mention "Object Teams" however I assume the following code exemplifies some anti-pattern since I don't see a business need for a nested nested class.

public class CACCIData {
...
    public CompanySearchResultsResult.CompanySearchResult mcCompanySearchResult = null;

    public static class CompanySearchResultsResult {
        public List<CompanySearchResult> CompanySearchResult 
            = new ArrayList<CompanySearchResult>();

        public static class CompanySearchResult {
// ...
        }
    }

Eclipse 2018-12 compile error: 'CACCIData$CompanySearchResultsResult' cannot be used as type anchor for an externalized role: is not a team (OTJLD 1.2.2(b)).

Upvotes: 1

Views: 154

Answers (1)

Gergely Bacso
Gergely Bacso

Reputation: 14651

Double-nested classes are syntactically valid. The code below works and prints the logical, predictable output:

public class Test {
    public static void main(String[] args) {
        new A().testPrintA();
    }
    public static class A {
        public void testPrintA() {
            System.out.println("Works from A.");
            new B().testPrintB();
        }
        public static class B {
            public void testPrintB() {System.out.println("Works from B.");}
        }
    }
}

Now on the "should you use it" side... It is opinionated, but I believe there won't be too many opportunities where this construct offers the best solution.

Upvotes: 1

Related Questions