How to override/extend an inner class from a subclass?

后端 未结 3 1677
清歌不尽
清歌不尽 2021-02-03 19:44

I want to change how a method of a class executes without overriding the method, and only overriding (or ideally extending) the inner class. Assume that I cannot change the fact

3条回答
  •  旧时难觅i
    2021-02-03 20:03

    I think you need a factory method for this. Consider the following example (derived from your snippet):

    static class A {
        static class Thing {
            public int value() {
                return 10 + value2();
            }
            public int value2() {
                return 10;
            }
        }
        protected Thing createThing() {
            return new Thing();
        }
        public String toString() {
            return Integer.toString(createThing().value());
        }
    }
    
    static class B extends A {
        static class Thing extends A.Thing {
            public int value2() {
                return 20; 
            }
        }
        @Override
        protected Thing createThing() {
            return new Thing(); // creates B.Thing
        }
    }
    
    public static void main(String[] args) {
        System.out.println(new B());
    }
    

    Output:

    30
    

提交回复
热议问题