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?<
Static methods are class-level methods, so no instance is required.
Non-static methods are instance methods. Hence an instance is required.
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.
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.
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