There was an instance field, but a class field that belongs to a class There is also that. As a concrete example, count how many instances were created There is something called count. [Example]
class Person{
public static int count = 0;
//...Abbreviation
Person(String firstName,...);{
Person.count++;
... //↑ By doing this, each time an instance is created, it will be added by 1.
class Person{
public static int count = 0;
//...Abbreviation
public static void printCount(){
System.out.println("total" + Person.count + "Is a person");
}
}
Class methods can be called even if no instance is created.
//<Main.java>At
class Main{
public static void main(String[]args){
Person.printCount();
Person person1 = new Person( //...Abbreviation);
Person.printCount();
}
}
output: 0 people in total 1 person in total
The content of the fullName created in the previous article was "firstName + lastName" I will write a concrete example of how to write when you want to add middleName ↓ (Since some instances do not have a middleName, they are indicated by conditional branching.)
class Person{
...
public String fullName(){
if (this.middleName == null){
return this.firstName + " " + this.lastName;
}else{
return this.firstname + " " + this.middleName + " " + this.lastName;
}
}
...
A mechanism used to prevent a defined object from being destroyed by touching it. An image like the inside of a personal computer. Until now, it was written as "public", but now it is written as "private".
To make it private and then safely get the value from outside the class A mechanism that returns the value of a field. Write "get field name".
A mechanism used when you want to change the value outside the class after setting it to private. Write "set field name".
//<Person.java>At...After writing the constructor ↓
...
public String getMiddleName() {
return this.middleName;
}
//First, define the getter, then define the setter
public void setMiddleName(String middleName) {
this.middleName=middleName;
}
...
//<Main.java>At...Person person1 = new Person("Yamada","Hanako"...);If it is written.
...
person1.setMiddleName("Claire"); //If you want to change it.
System.out.println("Middle name" + person1.getMiddleName() + "Changed to");
・ When defining a getter
public String getName(){
return this.name;
In the above case, I forget (), so review it carefully. Remember again.
To advance so that you can write the object orientation so far by yourself I will review how to write while using Progate and other sites. If you have any questions or findings, I will write them again.
Recommended Posts