I'm going to touch Java, so don't forget it (if you make a mistake, I'd appreciate it if you could comment) If you are not familiar with static and non-static methods, just for reference ...
If you are a beginner in the first place, why not add static to the method as a magic trick? I didn't understand the meaning and wrote it for the time being! Lol First look at the two codes below.
A.java
class A {
public static void main(String[] args){
calc(); //Call the calc method
}
static void calc(){ //calc is a static method
//Calculation process
}
}
A.java
class A {
public static void main(String[] args){
calc(); //Call the calc method
}
void calc(){ //calc is a non-static method
//Calculation process
}
}
Both programs are trying to call the calc method from the main method. However, programs that use the wrong static will be compiled when compiled. "Non-static methods cannot be referenced from static contexts" I get the error.
Why do I get such an error? ** static method (main) cannot directly access non-static method (calc) in the same class (A) </ font> ** Because it is supposed to be.
Now let's see how you can call methods in the same class.
There are two main ways to call a method in a class.
This is as described in [1. static method] above. If you add static to a method, it will be a shared method within the class, so it can be accessed from other methods.
It's difficult to understand in words, so I'll show it in code as well.
A.java
class A {
public static void main(String[] args){
A a = new A(); //Create an instance called a
a.calc(); //Call the calc method on instance a
}
void calc(){ //calc is a non-static method
//Calculation process
}
}
Isn't it not possible to access non-static methods in the same class from static methods? Some people may have thought. This method calls the ** calc method through ** instance a by creating an instance a of class A in the main method. Therefore, you are not directly accessing it, but you are accessing ** indirectly **, so you can call it.
It would be great if you could somehow understand static and non-static methods. Perhaps the reason for Java beginners to write static when writing a method is to prevent an error when called from the main method! Lol static may be attached to a variable. I will write an article about static variables next time.
Thank you for reading for me until the end. Natsu.
Recommended Posts