为什么使用方法本地抽象内部类 [英] Why use method local abstract inner classes

查看:101
本文介绍了为什么使用方法本地抽象内部类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可以与方法本地内部类一起使用的合法修饰符之一是abstract。

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

例如:

public class Outer {
    public void method(){
        abstract class Inner{
        }
    }
}

您是否有实际使用过的情况?

Is there any situation where you would actually use this?

你必须知道这个SCJP考试。

You have to know this for the SCJP exam.

推荐答案

原始问题中的一些无效假设。某些东西是合法/有效的Java并不意味着它是您需要使用或需要知道的东西。

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.

我不记得SCJP包含奇怪的案例问题。

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
    }

}

这篇关于为什么使用方法本地抽象内部类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆