内/匿名课程的最佳实践 [英] Best practice for inner/anonymous classes

查看:85
本文介绍了内/匿名课程的最佳实践的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

匿名类和静态内部类的最佳实践(设计和性能)是什么?

What's the best practise(design and performance wise) for anonymous classes and static inner classes?

我个人认为静态内部类提供了更好的封装,并且应该提供更好的性能,因为他们无法访问类外的最终变量。但是我从来没有真正质疑过这个问题。

Personally I would like to think that static inner classes provide better encapsulation and should give better performance as they dont have access to finalized variables outside their class. But I've never really questioned this.

我发现了一篇关于此事的帖子,但我觉得它实际上没有回答这个问题,只是人们个人的想法。

I found one post about this but I felt it didn't actually answer the question about, just peoples personal thought about it.

推荐答案

内部类(静态或非静态)与其封闭类的字段和方法具有完全相同的匿名类访问权限,静态内部类(实际上称为嵌套类)和(常规,非静态)内部类之间的区别在于静态内部类需要显式引用封闭类的实例来访问某些内容。当然,当你需要这样做时,它通常是在创建内部类的封闭类的实例上,因此使用非静态内部类更容易和更清晰。

Inner classes (static or not) have exactly the same access to their enclosing class' fields and methods as anonymous classes, the difference between static inner classes (actually called nested classes) and (regular, non-static) inner classes being that the static one need an explicit reference to an instance of the enclosing class to access something. Of course, when you need to do that, it's usually on the instance of the enclosing class that created the inner class, so it's easier and clearer to use a non-static inner class.

示例:


  • 内部类(非静态)

  • Inner class (non-static)

class A {
    private int field;

    private class B {
        public void doSomething() {
            field++; // Valid
        }
    }
}


  • 嵌套类(即静态内部类)

  • Nested class (i.e. "static inner class")

    class A {
        private int field;
    
        private static class B {
            public void doSomething(A a) {
                a.field++; // Valid
            }
        }
    }
    


  • 匿名类

  • Anonymous class

    class A {
        private int field;
    
        public void doSomething() {
            new Runnable() {
                @Override
                public void run() {
                    field++; // Valid
                }
            }
        }
    }
    


  • 您是否使用该辅助功能是另一个问题。如果您访问封闭类的私有字段,则会生成一个访问者,因此可能影响性能,因为调用方法的成本与访问字段的成本不同,但它在大多数情况下可能会忽略不计。在进行不基于任何测量的微优化之前,您应该首先编写正确的代码(在设计和功能方面)。无论如何,JIT编译器会为你做很多事情。

    Whether you use that accessibility is another question. If you do access private fields of the enclosing class, there'll be an accessor generated, so it could impact the performance as the cost of calling a method is not the same as accessing a field, but it will probably be negligible in most cases. You should always write correct code first (both in terms of design and functionality) before doing micro-optimizations not based on any measurement. The JIT compiler does a lot of things for you anyway.

    这篇关于内/匿名课程的最佳实践的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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