2 scenarios to use the static modifier

本文探讨了静态方法和变量的概念,解释了它们如何独立于类实例存在,并保持所有实例间的共享状态。此外,还讨论了静态成员的访问方式及其与实例成员的区别。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

utility-method-always-runs-the-same

Imagine you've got a utility class with a method that always runs the same way. It wouldn't matter which instance of the class performed the method—it would always behave exactly the same way. In other words, the method's behavior has no dependency on the state (instance variable values) of an object. So why, then, do you need an object when the method will never be instance-specific? Why not just ask the class itself to run the method?

keep-a-running-total-of-instances

Let's imagine another scenario: Suppose you want to keep a running count of all instances instantiated from a particular class. Where do you actually keep that variable? It won't work to keep it as an instance variable within the class whose instances you're tracking, because the count will just be initialized back to a default value with each new instance.

Static Variables and Methods


Variables and methods marked static belong to the class, rather than to any particular instance. In fact, you can use a static method or variable without having any instances of that class at all. You need only have the class available to be able to invoke a static method or access a static variable. static variables, too, can be accessed without having an instance of a class. But if there are instances, a static variable of a class will be shared by all instances of that class; there is only one copy.

A static method can't directly access a nonstatic (instance) variable, because there is no instance!

The same applies to instance methods; a static method can't directly invoke a nonstatic method.
Think static = class, nonstatic = instance.


Accessing Static Methods and Variables


The way we access a static method (or static variable) is to use the dot operator on the class name, as opposed to using it on a reference to an instance.

A syntax trick


This is a syntax trick to let you use an object reference variable to get to a static method or variable, but the static member is still unaware of the particular instance used to invoke the static member. In other words, the compiler cares only that reference variable is declared as which type.

redefine vs. override


Finally, remember that static methods can't be overridden! This doesn't mean they can't be redefined in a subclass, but redefining and overriding aren't the same thing. Let's take a look at an example of a redefined (remember, not overridden), static method: 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值