Now that I've learned a bit about Java, I'd like to write about static modifiers. This article is the 20th day article of SLP_KBIT Part 2 Advent Calendar 2016 --Qiita.
Please point out any mistakes.
Some people make heavy use of static because static methods can be called directly from the class without creating an instance. We call such people "static uncle" or not.
If you add a static modifier to a method or member variable, it becomes a static method or static variable. What changes with the static modifier is that you can access the method and member variables without new. In other words, static is -When defining a common method -When defining common properties ・ When you want to share common properties among multiple classes It is a qualifier used for.
There are various reasons for this, but for example, static methods and variables will affect everything that is referenced elsewhere if the value of the variable is changed in one place. Therefore, abusing static can be confusing.
Let's explain while actually looking at the code.
Human.java
public class Human {
private String name;
private int satiety; //Satiety
public Human(String name, int satiety) {
this.name = name;
this.satiety = satiety;
}
public void eat(int amountfood) {
this.satiety += amountfood;
}
}
The code above is a Human class for creating a human object. This class has two properties and two methods, all of which are non-static properties and methods. Non-static property methods are instance-specific. The "name" is unique to the instance because it is not that "humans" have a common name, but that each "individual" has it. In addition, "hunger" and "eating action" are also carried and taken individually by each person, so they are unique to the instance.
Now, let's add a static property to the Human class.
Human.java
public class Human {
static int count_Human = 0;
private String name;
private int satiety; //Satiety
Human(String name, int satiety) {
this.name = name;
this.satiety = satiety;
count_Human++;
}
public void eat(int amountfood) {
this.satiety += amountfood;
}
}
Added the static property "Number of people". When the Human method is called, it increases the "number of people". So why is the "number of people" static? That's because "number of people" is a class-specific property, not an instance-specific property. What is the "name" of "human"? I don't understand. Because the "name" belongs to the "individual". Then, what is the "number of people" of "humans"? You can answer when asked. Because "number of people" is a property of the "human" class. In this way, use static when you want to create class-specific properties and methods.
Static is useful, but abuse can be confusing as the values don't match and you don't know what code you wrote. So, let's use static well and do our best not to become a static uncle.
Quote: [Java] What is static?
Recommended Posts