Why use method local abstract inner classes

后端 未结 10 1706
名媛妹妹
名媛妹妹 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:08

    The are some invalid assumptions in the original question. That something is legal/valid Java doesn't mean that it is something that you need to use, or need to know.

    I can't recall that the SCJP contains odd corner case questions.

    I tried to come up with a case where I would have used an abstract class declared in a method, but everything looks very odd, and reeks of bad design. Here's however a code example that I came up with (still bad code design IMHO)

    public class BatchExecutor {
    
        public static enum ResultNotification {
            JMS,
            MAIL
        };
    
        public Runnable createRunnable(ResultNotification type) {
            abstract class Prototype implements Runnable {
                public void run() {
                    performBusinessLogic();
                    publishResult();
                }
    
                abstract void publishResult();
            }
    
            switch (type) {
                case JMS: {
                    return new Prototype() {
                        void publishResult() {
                            //Post result to JMS
                        }
                    };
                }
                case MAIL: {
                    return new Prototype() {
                        void publishResult() {
                            //Post result to MAIL
                        }
                    };
                }
            }
            return null;
        }
    
        private void performBusinessLogic() {
            //Some business logic
        }
    
    }
    

提交回复
热议问题