为什么我们可以拥有静态最终成员但在内部类中不能使用静态方法? [英] Why can we have static final members but cant have static method in an inner class?

查看:175
本文介绍了为什么我们可以拥有静态最终成员但在内部类中不能使用静态方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么我们可以拥有静态最终成员但不能在非静态内部类中使用静态方法?

Why can we have static final members but cant have static method in an non static inner class ?

我们可以访问外部类之外的内部类的静态最终成员变量而不实例化内部类吗?

Can we access static final member variables of inner class outside the outer class without instantiating inner class ?

推荐答案

你可以在静态内部类中使用静态方法。

YOU CAN have static method in a static "inner" class.

public class Outer {
    static String world() {
        return "world!";
    }
    static class Inner {
        static String helloWorld() {
            return "Hello " + Outer.world();
        }
    }   
    public static void main(String args[]) {
        System.out.println(Outer.Inner.helloWorld());
        // prints "Hello world!"
    }
}

确切地说, Inner 根据JLS术语称为嵌套类( 8.1.3 ):

To be precise, however, Inner is called a nested class according to JLS terminology (8.1.3):


内部类可以继承不编译的静态成员 - 时间常数,即使他们可能不会声明它们。不是内部类的嵌套类可以根据Java编程语言的通常规则自由地声明静态成员。

Inner classes may inherit static members that are not compile-time constants even though they may not declare them. Nested classes that are not inner classes may declare static members freely, in accordance with the usual rules of the Java programming language.






此外,它的 NOT 完全正确,内部类可以有静态最终成员;更确切地说,它们还必须是编译时常量。以下示例说明了区别:


Also, it's NOT exactly true that an inner class can have static final members; to be more precise, they also have to be compile-time constants. The following example illustrates the difference:

public class InnerStaticFinal {
    class InnerWithConstant {
        static final int n = 0;
        // OKAY! Compile-time constant!
    }
    class InnerWithNotConstant {
        static final Integer n = 0;
        // DOESN'T COMPILE! Not a constant!
    }
}

为什么允许编译时常量上下文很明显:它们在编译时内联。

The reason why compile-time constants are allowed in this context is obvious: they are inlined at compile time.

这篇关于为什么我们可以拥有静态最终成员但在内部类中不能使用静态方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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