making an instance before calling non static method in java

后端 未结 4 1572
长发绾君心
长发绾君心 2021-01-20 16:53

Hi could someone please explain to me why you have to create an instance before calling a non static method to the main function in java? What is the reasoning behind this?<

4条回答
  •  醉话见心
    2021-01-20 17:23

    Because, they are instance members,to access them you need instance.

    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.

    So now your second question about 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

提交回复
热议问题