编程语言
首页 > 编程语言> > 【Java学习】-the static keyword

【Java学习】-the static keyword

作者:互联网

静态主方法只能访问静态变量, 如果要访问动态变量,必须将变量实例化。

在JAVA程序中,除了主静态方法以及类方法之外,其他在该类下定义的实例变量、实例方法,在主类方法中调用时必须要将其实例化,就是要加上对象的引用。

Ordinarily, when you create a class you are describing how objects of that class look and how they will behave.

You don't actually get an object until you create one using new, and at that point, storage is allocated and methods become available.

There are two situations in which this approach is not sufficient.

One is if you want to have only a single piece of storage for a particular field, regardless of how many objects of that class are created,

or even if no objects are created.

The other is if you need a method that isn't associated with any particular object of this class. That is, you need a method that you can 

call even if no objects are created.

You can achieve both of these effects with the static keyword.

When you say something is static, it means that particular field or method is not tied to any particular object instance of that class.

So even if you've never created an object of that class you can call a static method or access a static field.

With ordinary, non-static fields and methods, you must create an object and use that object to access the field or method, since

non-static fields and methods must know the particular object they are working with.

Using the class name is the preferred way to refer to a static variable.

 

标签:Java,keyword,created,object,method,static,particular,class
来源: https://www.cnblogs.com/yidianling/p/15894532.html