Methods can be classified as either static or non-static. Here are the differences between these two types of methods:
-
Static methods are associated with the class itself, not with any particular instance of the class. Non-static methods, on the other hand, are associated with an instance of the class.
-
Static methods can be called without creating an instance of the class. Non-static methods, on the other hand, can only be called on an instance of the class.
-
Static methods can only access static variables and other static methods. Non-static methods can access both static and non-static variables and methods.
-
Static methods are often used for utility functions that do not depend on the state of any particular instance of a class. Non-static methods are often used for methods that operate on the state of an instance of a class.
public class Main {
static void directUsage() {
System.out.println("Something from directUsage Method. ");
}
public void mustUseObjects() {
System.out.println("I can be used only from Objects ");
}
public static void main(String[] args) {
directUsage();
Main newObj = new Main();
newObj.mustUseObjects();
}
}
Here's a block-by-block breakdown of the program:
public class Main {
static void directUsage() {
System.out.println("Something from directUsage Method. ");
}
In this block, we define a static method named "directUsage" that simply prints out a message to the console.
public void mustUseObjects() {
System.out.println("I can be used only from Objects ");
}
In this block, we define a non-static method named "mustUseObjects" that also prints out a message to the console.
public static void main(String[] args) {
directUsage();
Main newObj = new Main();
newObj.mustUseObjects();
}
In this block, we define the main method which is the entry point for the program. Inside this method, we call the static method "directUsage" directly on the class. Then we create an instance of the Main class named "newObj" using the "new" keyword. Finally, we call the non-static method "mustUseObjects" on the "newObj" instance.
When we run this program, it will output the following to the console:
Something from directUsage Method.
I can be used only from Objects
This program demonstrates that static methods can be called directly on the class without the need to create an instance of the class. Non-static methods, on the other hand, can only be called on an instance of the class.
No comments:
Post a Comment