为什么类在Java中被声明为静态? [英] Why is class declared as static in Java?

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

问题描述

我在 java 中看到类被声明为 static ,但很困惑:

因为类用于创建对象,并且不同的对象具有不同的内存分配。

那么,当声明类时,使用什么static是否意味着成员变量都是 static

这是否有意义? p>

I've seen class been declared as static in java, but confused:
Since class is used to create objects, and different objects have different memory allocations.
Then what is "static" used for when declaring a class?Does it mean the member variables are all static?
Does this make sense?

推荐答案

首先,你不能做顶级类的静态。您只能使嵌套类静态。通过使嵌套类静态你基本上说你不需要嵌套类的实例从外部使用它 class / top -level-class

Firstly you cannot make top-level-class static. you can only make an nested class static. By making an nested class static you basically are saying that you don't need an instance of the nested class to use it from your outer class/top-level-class.

示例:

class Outer {

static class nestedStaticClass {

//its member variables and methods (don't nessarily need to be static)
//but cannot access members of the enclosing class
}

public void OuterMethod(){
//can access members of nestedStaticClass w/o an instance
}
}

另外,在内部类中声明静态字段是非法的,除非它们是常量(static final)。因为静态嵌套类不被视为内部类,你可以在这里声明静态成员。

Also to add, It is illegal to declare static fields inside an inner class unless theya re constants (static final). as static nested class isn't considered an inner class you can declare static members here.


类可以嵌套在嵌套类中吗? p>

Can class be nested in nested class?

在单个字中是,看下面的Test,嵌套的(Inner类的)和嵌套的静态类都可以嵌套类'''em'。但请记住,您只能在顶级类中声明一个静态类,在嵌套内部类中声明它是非法的。

In single word yes, Look the below Test, both nested(Inner class's) and nested static class can have nested class'sin 'em. But remember you can only declare a static class inside a top-level class, It is illegal to declare it inside an nested inner class.

public class Test {
    public class Inner1 {
        public class Inner2 {
            public class Inner3 {

            }
        }
    }
    public static class nested1 {
        public static class nested2 {
            public static class nested3 {

            }
        }   
    }
}

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

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