JAVA 非访问修饰符

JAVA Non Access Modifier|JAVA Tutorials Point

学习完了JAVA的基础知识之后,发现对非访问修饰符的掌握还是很薄弱,不知道有时候该用哪种修饰符,有点搞不清,这篇文章结合中外两种的网站来全面的复习一下。

static 修饰符,用来修饰类方法和类变量。
The static modifier for creating class methods and variables.

静态变量
static 关键字用来声明独立于对象的静态变量,无论一个类实例化多少对象,它的静态变量只有一份拷贝。 静态变量也被称为类变量。局部变量不能被声明为 static 变量。

静态方法
static 关键字用来声明独立于对象的静态方法。静态方法不能使用类的非静态变量。静态方法从参数列表得到数据,然后计算这些数据。

The static keyword is used to create variables that will exist independently of any instances created for the class. Only one copy of the static variable exists regardless of the number of instances of the class.
Static variables(静态变量) are also known as class variables. Local variables cannot be declared static.

Static Methods
The static keyword is used to create methods that will exist independently of any instances created for the class.

Static methods do not use any instance variables of any object of the class they are defined in. Static methods take all the data from parameters and compute something from those parameters, with no reference to variables.

Class variables and methods can be accessed using the class name followed by a dot and the name of the variable or method.

example

public class InstanceCounter {

   private static int numInstances = 0;

   protected static int getCount() {
      return numInstances;
   }

   private static void addInstance() {
      numInstances++;
   }

   InstanceCounter() {
      InstanceCounter.addInstance();
   }

   public static void main(String[] arguments) {
      System.out.println("Starting with " + InstanceCounter.getCount() + " instances");

      for (int i = 0; i < 500; ++i) {
         new InstanceCounter();
      }
      System.out.println("Created " + InstanceCounter.getCount() + " instances");
   }
}

final 修饰符,用来修饰类、方法和变量,final 修饰的类不能够被继承,修饰的方法不能被继承类重新定义,修饰的变量为常量,是不可修改的。
The final modifier for finalizing the implementations of classes, methods, and variables.

abstract 修饰符,用来创建抽象类和抽象方法。
The abstract modifier for creating abstract classes and methods.

synchronized 和 volatile 修饰符,主要用于线程的编程。
The synchronized and volatile modifiers, which are used for threads.

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • 为了实现一些其他的功能,Java 也提供了许多非访问修饰符。 static 修饰符,用来修饰类方法和类变量。 fi...
    进击的叉烧阅读 288评论 0 0
  • Java语言提供了很多修饰符,主要分为以下两类: 访问修饰符 非访问修饰符 修饰符用来定义类、方法或者变量,通常放...
    薇薇和艾艾阅读 172评论 0 0
  • 访问修饰符 现在,让我们来了解main方法前面的 public 关键字。 public static void m...
    朱兰Juran阅读 507评论 0 1
  • 1、Java中间件,分布式系统、分布式缓存、消息队列 JAVA中间件:包括服务框架中间件:解决集群间的访问通信问题...
    LP帅气的昵称阅读 667评论 0 0
  • Java修饰符——菜鸟教程https://www.runoob.com/java/java-modifier-ty...
    David_Rao阅读 566评论 0 3

友情链接更多精彩内容