【Java学习】-the static keyword

2022/2/15 1:12:17

本文主要是介绍【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学习】-the static keyword的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程