Java – why do internal static classes extend external abstract classes?

I'm trying to extend some existing code that implements trees using composite patterns As expected, there is an interface

I encountered this other pattern in the code I'm using, where the concrete class is implemented as a static inner class and extends the external abstract class At the same time, they are from the outside (?) Interface nodes implement static internal interfaces (NODEA, NodeB, nodec)

public interface Node {
  public static interface NodeA {}
  public static interface NodeB {}
  public static interface NodeC {}
}

public abstract class AbstractNode implements Node {

  public void foo() {
    ...
  }

  public void bar() {
    ...
  }

  ...

  public static class ConcreteNodeA extends AbstractNode implements Node.NodeA {
    ...
  }

  public static class ConcreteNodeB extends AbstractNode implements Node.NodeB {
    ...
  }

  public static class ConcreteNodeC extends AbstractNode implements Node.NodeC {
    ...
  }
}

What's the use of this model? Through years of Java experience, I've never seen anything like this before My intuition says it's a huge code smell because concrete classes are often instantiated and used multiple times throughout the code Anyway, I'm not worried about efficiency, but it's hard to maintain and extend! It makes more sense to put them in different courses, doesn't it?

I've searched more formal references to prove that this is a good idea, but I haven't found anything yet

There are no compilation errors and the code is perfect

Solution

This pattern is actually very common when describing related families of types, such as nodes of trees

One reason is very simple, it is a convenient grouping; These classes are often individually small, and centralizing them all in one place can make it easier to read and maintain, and send signals that they are closely coupled families and intend to use together

A more compelling reason is that it can provide a form of sealed classes By using a private constructor in an abstract class, only the inner class can access it, which means that the inner class is the only allowed subclass

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>