It went well up to the main method. However, it suddenly became difficult after the appearance of "methods" and "objects".
By making it an object, you can call variables and methods set in your favorite file at your favorite timing. By making it a method, it becomes possible to skip the saved or processed data as a return value and receive it as an argument. With these, you can freely pass data to any file.
I will explain what that means.
Main1.java
public class Main1 {
public static void main(String[] args) {
Human human = new Human();
human.name = "Between";
human.hello();
}
}
Human.java
public class Human {
String name;
public void hello(){
System.out.println(name +"Hi,");
}
}
Aida's, Hello
Isn't it necessary to prepare two files? → Is it possible to make it only with main?
Main2.java
public class Main2 {
public static void main(String[] args) {
String name;
name = "Between";
System.out.println(name +"Hi,");
}
}
Aida's, Hello
I found that I didn't need any objects or methods in the following cases:
--One data (name) to save --One data processing (output using name)
Earlier there was only one "Aida-san", What happens if "Ueda-san" is also added?
Main2.java
public class Main2 {
public static void main(String[] args) {
String name;
name = "Between";
//■ ① Add "Ueda".
name = "Ueda";
//■ "Hello" for the ② "Between" Mr. intact
System.out.println(name +"Hi,");
//■ add the "Hello" for the ③ "Ueda" Mr.
System.out.println(name +"Hi,");
}
}
Mr. Ueda, Hello
Mr. Ueda, Hello
If you try to do it only with the main method,
--The same variable (variable is overwritten) cannot be used. --Since variables cannot be used, data processing does not work well. (Only "Ueda" appears.)
Main2.java
public class Main2 {
public static void main(String[] args) {
String name1;
String name2;
name1 = "Between";
name2 = "Ueda";
System.out.println(name1 +"Hi,");
System.out.println(name2 +"Hi,");
}
}
When there are two or more data you want to save,
--You have to prepare two variables. --You have to think about variable names. ――When you look at it later, you may not know which variable contains "which data".
It is better to separate by object than to process only by main method I found the following.
--Data can be saved with the same variable name. --You can retrieve data at any time you like.
In the next post, "Summary" With the part that "data can be retrieved at any time" Be able to explain the benefits of using "methods".
Recommended Posts