Why use method local abstract inner classes

后端 未结 10 1766
名媛妹妹
名媛妹妹 2021-02-05 04:45

One of the legal modifiers you can use with method local inner classes is abstract.

For example:

public class Outer {
    public void method(){
        a         


        
10条回答
  •  说谎
    说谎 (楼主)
    2021-02-05 05:14

    Check out the section titled "Hierarchies of Inner Classes" on this page.

    The gist is that you can treat the inner class as just another abstract member that needs to be overridden/implemented. I don't necessarily agree with it (I would probably just define the inner class separately), but I've seen things like this in the wild.

    Here's their example code:

    public abstract class BasicMonitorScreen {
       private Dimension resolution;
    
       public BasicMonitorScreen(final Dimension resolution) {
          this.resolution = resolution;
       }
    
       public Dimension getResolution( ) {
          return this.resolution;
       }
    
       protected abstract class PixelPoint {
          private int x;
    
          private int y;
    
          public PixelPoint(final int x, final int y) {
             this.x = x;
             this.y = y;
          }
    
          public int getX( ) {
             return x;
          }
    
          public int getY( ) {
             return y;
          }
       }
    }
    
    public class ColorMonitorScreen extends BasicMonitorScreen {
       public ColorMonitorScreen(final Dimension resolution) {
          super(resolution);
       }
    
       protected class ColorPixelPoint extends PixelPoint {
          private Color color;
          public ColorPixelPoint(final int x, final int y, final Color color) {
             super(x, y);
             this.color = color;
          }
    
          public Color getColor( ) {
             return this.color;
          }
       }
    }
    

提交回复
热议问题