gpt4 book ai didi

java - 在java中调用非静态方法之前创建一个实例

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:51:03 27 4
gpt4 key购买 nike

嗨,有人可以向我解释一下为什么在调用 Java 中的主函数的非静态方法之前必须创建一个实例吗?这背后的原因是什么?

最佳答案

因为,它们是实例成员,要访问它们,您需要实例。

When a number of objects are created from the same class blueprint, they each have their own distinct copies of instance variables. In the case of the Bicycle class, the instance variables are cadence, gear, and speed. Each Bicycle object has its own values for these variables, stored in different memory locations.

那么现在你的第二个问题是关于 static

Sometimes, you want to have variables that are common to all objects. This is accomplished with the static modifier. Fields that have the static modifier in their declaration are called static fields or class variables. They are associated with the class, rather than with any object. Every instance of the class shares a class variable, which is in one fixed location in memory. Any object can change the value of a class variable, but class variables can also be manipulated without creating an instance of the class.

Understanding Instance and Class Members

关于java - 在java中调用非静态方法之前创建一个实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18671081/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com