Java Inner Class extends Outer Class

后端 未结 3 1583
情歌与酒
情歌与酒 2021-02-08 07:31

There are some cases in Java where an inner class extends an outer class.

For example, java.awt.geom.Arc2D.Float is an inner class of java.awt.geom.Arc2D, and also exten

3条回答
  •  误落风尘
    2021-02-08 08:20

    There are two cases of inner-classes:

    • static inner-classes. The inner-class does not keep reference to the outer-class.

    • non-static inner-classes. The inner-class does keep a reference to the outer-class.

    The case of a static inner-class that extends the outer-class is not as interesting as the non-static inner-class extending the outer-class.

    What happens with the latter is: to create the inner-class, one needs a reference to the outer-class. However, as the inner-class is an instance of the outer-class, it also accepts a reference to another instance of the inner-class, to be used as outer-class.

    Let's look at some code:

    Outer a = new Outer();
    Outer.Inner b = a.new Inner();
    
    // Only possible when Inner extends Outer:
    Outer.Inner c = a.new Inner().new Inner();
    

    If you know the builder pattern, this can be used to have an OOP-version of it:

    public abstract class Command {
    
        // Not possible to create the command, else than from this file!
        private Command() {
        }
    
        public abstract void perform();
    
        public static class StartComputer extends Command {
            public void perform() {
                System.out.println("Starting Computer");
            }
        }
    
        public class OpenNotepad extends Command {
            public void perform() {
                Command.this.perform();
                System.out.println("Opening Notepad");
            }
        }
    
        public class ShutdownComputer extends Command {
            public void perform() {
                Command.this.perform();
                System.out.println("Shutting Computer");
            }
        }
    
    }
    

    Which is used as: new Command.StartComputer().new OpenNotepad().new ShutdownComputer().perform();.

提交回复
热议问题