Here, we will introduce class methods. Variables in a class that have static in their head at the time of declaration are called class variables. Similarly, a method that has static in its head when it is declared is called a class method. You can read it if you know the structure of the class and how to write and call the method. Also, the access specifier is omitted. (I think you can read it without knowing it.)
Class methods do not instantiate when called. Use the class name when calling. There are some useful things and things to be aware of.
I summarized how to write and use class methods.
The way to write a class method is as follows.
public class class name{
public static return type method name(Argument type Argument){
//The contents of the method
}
}
It just has static. So there is no such thing as a configuration. However, static methods can only be used with static methods.
Class method using class name without instance
name of the class.Method name(Argument type Argument);
Call like.
Next, let's write an example of a class method. The class name is Call class.
public void Call(){
public static void Dog(){
System.out.println("Bow-wow");
}
public static void Cat(){
System.out.println("Meow meow");
}
public static void Monkey(){
System.out.println("Ukey");
}
}
Call the static methods of this class from the main method. Note that we are calling using the class name instead of instantiating it.
public class MainMethod(){
public static void main(String[] args){
Call.Dog();
Call.Cat();
Call.Monkey();
}
}
Now like this
Bow-wow
Meow meow
Ukey
Will be the output.
Class methods are not instantiated. In other words, it cannot be distinguished for each instance. For example, in the following class, the number of times the method in the class for each instance is called is counted by the variable instance_count. This variable instans_count makes sense because it is instantiated. So static methods don't make sense.
public class ClassValue2 {
private int s = 3;
private static int static_count = 0;
private int instans_count = 0;
public void add(int num){
s = num + s;
static_count = static_count + 1;
instans_count = instans_count + 1;
}
public void substract(int num){
s = -num + s;
static_count = static_count + 1;
instans_count = instans_count + 1;
}
public void multiple(int num){
s = num*s;
static_count = static_count + 1;
instans_count = instans_count + 1;
}
public void division(int num){
s = 1/num*s;
static_count = static_count + 1;
instans_count = instans_count + 1;
}
public void confirmation(){
System.out.println("static_count:" + static_count);
System.out.println("instans_count:" + instans_count);
System.out.println("s:" + s);
}
}
Recommended Posts