making an instance before calling non static method in java

南楼画角 提交于 2019-12-02 02:03:07

问题


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?


回答1:


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




回答2:


Static methods are class-level methods, so no instance is required.

Non-static methods are instance methods. Hence an instance is required.




回答3:


Without this, object-oriented programming would really be no different from traditional procedural programming. When you execute a non-static function, you can access all the variables belonging to the object.

That being said, look carefully at the functions you're calling to see if they can remain static. A static function is more portable, and less likely to cause side-effects.




回答4:


All the Static things of a class always belongs to a class and they are treated as a properties of the class .That's why they can be called by their name in that class, and called outside the class with the class name.

All the Non-Static things of a class always belongs to an object, they are always treated as properties of an object. That's why they can only be called after creating an object by a (.) dot operator.



来源:https://stackoverflow.com/questions/18671081/making-an-instance-before-calling-non-static-method-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!