首页 > 代码库 > Java关键字--static
Java关键字--static
在Java中,将关键字static分为三部分进行讨论,分别为Java静态变量、Java静态方法、Java静态类
Java Static Variables
- Java instance variables are given separate memory for storage. If there is a need for a variable to be common to all the objects of a single java class, then the static modifier should be used in the variable declaration.
- Any java object that belongs to that class can modify its static variables.
- Also, an instance is not a must to modify the static variable and it can be accessed using the java class directly.
- Static variables can be accessed by java instance methods also.
- When the value of a constant is known at compile time it is declared ‘final’ using the ‘static’ keyword.
(1)类的非静态变量会被每一个被实例化的对象分配一个内存空间,而静态变量会被类所有实例化的对象共享同一块内存空间。
(2)类的任何一个实例化对象对该静态变量的操作都会改变该静态变量的值
(3)可以直接通过 ClassName.static-Variable 对静态变量进行访问
(4)static 和final用来修饰成员变量和成员方法,可简单理解为“全局常量”。
Java Static Methods
- Similar to static variables, java static methods are also common to classes and not tied to a java instance.
- Good practice in java is that, static methods should be invoked with using the class name though it can be invoked using an object. ClassName.methodName(arguments) or objectName.methodName(arguments)
- General use for java static methods is to access static fields.
- Static methods can be accessed by java instance methods.
- Java static methods cannot access instance variables or instance methods directly.
- Java static methods cannot use the ‘this’ keyword.
(1)静态方法可以直接通过类名调用,任何的实例也都可以调用。
(2)静态方法中不能用this和super关键字,不能直接访问所属类的实例变量和实例方法(就是不带static的成员变量和成员成员方法),只能访问所属类的静态成员变量和成员方法 (这点和C++中是一致的)
(3)因为static方法独立于任何实例,因此static方法必须被实现,而不能是抽象的abstract。
Java Static Classes
- For java classes, only an inner class can be declared using the static modifier.
- For java a static inner class it does not mean that, all their members are static. These are called nested static classes in java
(1)只有内部类才能被声明为静态类
Java关键字--static
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。