为什么在Java中不能将类声明为静态?
当前回答
默认情况下,顶级类是静态的。默认情况下,内部类是非静态的。您可以通过显式地将内部类标记为静态来更改它们的默认值。顶级类由于是顶级类,所以不能具有非静态语义,因为没有父类可以引用。因此,无法更改顶级类的默认值。
其他回答
如果使用静态类的好处是不实例化对象并使用方法,那么只需将类声明为公共,并将此方法声明为静态。
当然可以,但只能是内部嵌套类。在这里,它意味着嵌套类的实例不需要外部类的封闭实例。
但是对于顶级类,语言设计者想不出任何有用的关键字,所以它是不允许的。
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();
}
}
您可以在Eclipse中的PlatformUI中查看带有静态方法和私有构造函数的类,该类本身是final的。
public final class <class name>
{
//static constants
//static memebers
}
我认为这可能就像喝一杯咖啡一样简单! 看看这个。 定义类时不显式使用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);
}
}
推荐文章
- 如何在java中格式化持续时间?(如格式H:MM:SS)
- urlencoder .encode(字符串)已弃用,我应该使用什么代替?
- javax.transaction.Transactional vs . org.springframework.transaction.annotation.Transactional
- Java 8接口方法中不允许“同步”的原因是什么?
- 如何找到Java堆大小和内存使用(Linux)?
- 使用Enum实现单例(Java)
- RabbitMQ与通道和连接之间的关系
- buildSessionFactory()配置方法在Hibernate中已弃用?
- Spring MVC -如何获得所有的请求参数在一个地图在Spring控制器?
- 如何在Java中按两个字段排序?
- 文件之间的差异。路径中的分隔符和斜杠
- 在方法参数中使用NotNull注释
- Spring MVC中处理可选参数的@RequestParam
- Tomcat:如何查找正在运行的Tomcat版本?
- “java”、“javaw”和“javaws”之间有什么区别?