为什么我们在 Java 中将类设为静态? [英] Why do we make a class static in java?

查看:32
本文介绍了为什么我们在 Java 中将类设为静态?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能的重复:
Java 中的静态嵌套类,为什么?

我知道 java 中的静态字段.但是不知道为什么要创建静态类.有什么想法吗?

I know about the static fields in java. But don't know why we create a static class. Any idea?

推荐答案

class Outer {
    int a;
    class Inner {
        void test() {
            System.out.println(a);
        }
    }
}

通常,内部类可能会引用其所属类的字段,如您在上面的(伪)示例中所见.所以Inner的实例可以访问Outer中的字段/方法/等.

Normally, an inner class may reference its owning class's fields, as you can see in the (pseudo) sample above. So an instance of Inner may access fields / methods / etc in Outer.

但是这要求每个内部实例都有一个与之关联的外部实例.所以你做不到

But this requires every Inner instance to have an Outer instance associated with it. So you cannot do

new Inner();

但必须这样做

new Outer().new Inner();

在某些情况下,这是不可取的——比如你需要确保你的外部实例可以被垃圾收集,或者你需要使内部实例独立于外部.在这种情况下,您可以将其更改为

In some cases this is not desirable - say you need to ensure that your Outer instances may get garbage collected, or that you need to make Inner instances independent of Outer. In that case you may change it to

static class Inner {

在这种情况下,现在您可能不再像以前一样引用a",但作为交换,您根本不需要拥有 Outer 的实例来拥有 Inner 的实例.

in which case now you may no longer reference "a" as before, but in exchange you don't need to have an instance of Outer at all to have instances of Inner.

这篇关于为什么我们在 Java 中将类设为静态?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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