In this lecture, we are going to talk about static and non-static methods.
Static
The static method can be used to access without creating an object. It is used to construct methods that will exist regardless of whether or not any instance of the class is generated. Any method that uses a static keyword is referred to as a static method.
Features
The static methods can be accessed directly. A static method is a part of a class rather than an instance of that class. Every instance of a class has access to the method. It has access to class variables (static variables) without using the class’s object. Only static data is accessed by a static method.
Example Code
// Static method static void staticMethod() { System.out.println("Static methods can be called without creating objects"); } public static void main(String[] args) { staticMethod(); }
Calling with Class Name
We also call a static function with the class name just like below without creating an object.
//Main is a Class //staticMethod() is a method Main.staticMethod();
Non Static Method
Non Static functions are not allowed to call them without an object. One of the major reasons is our Main function is also a static function, that’s why we are not any non-static function in the static function. the method is below:
void nonStaticMethod() { System.out.println("Non Static Method"); }
Instance & Static Method
#BeingCodeStuffer