为什么在Java中不能将类声明为静态?
当前回答
如上所述,一个类不能是静态的,除非它是另一个类的成员。
如果你想要设计一个“不能有多个实例”的类,你可能想要研究一下“单例”设计模式。
这里是初学者单例信息。
警告:
如果您正在考虑使用 单例模式,抵制与所有 你的可能。这是最简单的方法之一 设计模式来理解,可能 最受欢迎的,绝对是 大多数滥用。 (来源:JavaRanch,如上图所示)
其他回答
我认为这可能就像喝一杯咖啡一样简单! 看看这个。 定义类时不显式使用static关键字。
public class StaticClass {
static private int me = 3;
public static void printHelloWorld() {
System.out.println("Hello World");
}
public static void main(String[] args) {
StaticClass.printHelloWorld();
System.out.println(StaticClass.me);
}
}
这不是静态类的定义吗? 我们只使用绑定到类的函数。 注意,在这种情况下,我们可以在该嵌套中使用另一个类。 看看这个:
class StaticClass1 {
public static int yum = 4;
static void printHowAreYou() {
System.out.println("How are you?");
}
}
public class StaticClass {
static int me = 3;
public static void printHelloWorld() {
System.out.println("Hello World");
StaticClass1.printHowAreYou();
System.out.println(StaticClass1.yum);
}
public static void main(String[] args) {
StaticClass.printHelloWorld();
System.out.println(StaticClass.me);
}
}
public class Outer {
public static class Inner {}
}
... 它可以被声明为静态的——只要它是一个成员类。
来自JLS:
成员类可以是静态的,在这种情况下,它们不能访问周围类的实例变量;或者它们可能是内部类(§8.1.3)。
在这里:
static关键字可以在非内部类t的主体中修改成员类型C的声明。它的作用是声明C不是内部类。就像T的静态方法在其主体中没有T的当前实例一样,C也没有T的当前实例,也没有任何词汇上的封装实例。
静态关键字对于顶级类没有任何意义,因为顶级类没有外围类型。
In addition to how Java defines static inner classes, there is another definition of static classes as per the C# world [1]. A static class is one that has only static methods (functions) and it is meant to support procedural programming. Such classes aren't really classes in that the user of the class is only interested in the helper functions and not in creating instances of the class. While static classes are supported in C#, no such direct support exists in Java. You can however use enums to mimic C# static classes in Java so that a user can never create instances of a given class (even using reflection) [2]:
public enum StaticClass2 {
// Empty enum trick to avoid instance creation
; // this semi-colon is important
public static boolean isEmpty(final String s) {
return s == null || s.isEmpty();
}
}
如果使用静态类的好处是不实例化对象并使用方法,那么只需将类声明为公共,并将此方法声明为静态。
我们在java中编写的所有代码都包含在一个类中。每当我们运行一个类时,JVM都会实例化一个对象。JVM可以创建许多对象,根据定义,静态意味着对所有对象都有相同的复制集。
所以,如果Java允许顶级类是静态的,无论何时你运行一个程序,它都会创建一个对象,并保持在相同的内存位置上重写。
如果你只是在每次运行时替换对象,那么创建它有什么意义呢?
这就是Java摆脱顶级类静态的原因。
可能有更具体的原因,但这对我来说更合乎逻辑。
推荐文章
- 在流中使用Java 8 foreach循环移动到下一项
- 访问限制:'Application'类型不是API(必需库rt.jar的限制)
- 用Java计算两个日期之间的天数
- 如何配置slf4j-simple
- 在Jar文件中运行类
- 带参数的可运行?
- 我如何得到一个字符串的前n个字符而不检查大小或出界?
- 我可以在Java中设置enum起始值吗?
- Java中的回调函数
- c#和Java中的泛型有什么不同?和模板在c++ ?
- 在Java中,流相对于循环的优势是什么?
- Jersey在未找到InjectionManagerFactory时停止工作
- 在Java流是peek真的只是调试?
- Recyclerview不调用onCreateViewHolder
- 将JSON字符串转换为HashMap