【问题标题】:Java Private Static vs Private method inside a class类中的Java私有静态与私有方法
【发布时间】:2022-11-20 03:17:34
【问题描述】:

有人能解释一下在什么情况下我们使用私有静态方法还是只在类中使用私有方法?

我的困惑来自于它们都是私有方法,所以我们无法调用

他们无论如何都来自班级之外(这违背了关键字static的目的)。

【问题讨论】:

  • static 表示它不是实例方法。它没有名为this 的变量。它无权访问实例变量。调用时,它不会通过其class 的实例调用。

标签: java static private


【解决方案1】:

非静态方法和静态方法(无论它们是私有的还是公共的)之间的主要区别 - 将 this 作为隐藏参数隐式传递给非静态方法

因此,即使方法是私有的并且只能在类本身内调用 - 最终它是性能差异,在数字处理应用程序中它会产生可衡量的差异

这是天真的测量:

public class Test {
    public static class Calc {
        public long sum1() {
            long r = 0;
            for (long i = 1; i < 10_000_000_000L; i++)
                r += sum(i, i);
            return r;
        }

        public long sum2() {
            long r = 0;
            for (long i = 1; i < 10_000_000_000L; i++)
                r += sum_static(i, i);
            return r;
        }

        private long sum(long a, long b) {
            return a + b;
        }

        private static long sum_static(long a, long b) {
            return a + b;
        }
    }

    public static void main(String[] args) {
        final Calc c = new Calc();
        final long t1 = System.currentTimeMillis();
        for (int i = 0; i < 10; i++)
            System.out.println(c.sum1());
        final long t2 = System.currentTimeMillis();
        for (int i = 0; i < 10; i++)
            System.out.println(c.sum2());
        final long t3 = System.currentTimeMillis();

        System.out.println("non static " + (t2 - t1));
        System.out.println("    static " + (t3 - t2));
    }
}

静态版本大约快 10% (YMMW)

【讨论】:

    猜你喜欢
    • 2012-07-14
    • 2017-05-23
    • 1970-01-01
    • 1970-01-01
    • 2016-06-28
    • 2010-11-04
    • 1970-01-01
    • 1970-01-01
    • 2014-06-19
    相关资源
    最近更新 更多