You can call a method of a class by using class name.method name (). [Example]
Main.java
class Main {
public static void main(String[] args) {
Person.hello(); //Person is the class name and hello is the method
}
}
Person.java
class Person { //Person is the class name
public static void hello() { //hello is the method
System.out.println("Good morning");
}
}
Call the Person in Person.java class with Person.hello (); in Main.java as above. By the way, the definition of the class is "class class name". Make sure the first letter of the class name is capitalized and the file name is "classname.java". [Example 2]
Main.java
public class Main {
public static void main(String[] args) {
Person.nameData(Person.fullName("Sato", "Taro"), 20); //Person is the class name and nameData is the method. Person.The same is true for fullName
}
}
Person.java
class Person {
public static void nameData(String name, int age) { //nameData is the method
System.out.println("my name is" + name + "so" + "Age is" + age + "歳soす");
}
public static String fullName(String firstName, String lastName) {
return firstName + " " + lastName;
}
}
The result above is "My name is Taro Sato and my age is 20".
This is because the main class is a class for execution, and the Person class is a division of roles that organizes logic. Java executes classes, not files. Only classes that have a main method can be executed at runtime (classes that do not have a main method are called from other classes and used). Also, regardless of the class name, the main method is called at runtime (because it is a Main class, the main method is not called).
It is to use a class created by another person. Such a class is called an external library and can be used by loading it into your own program. Use import to make an external library available to your program. Let's say "import java.lang.Math" above the class definition. Methods in the Math class have the meaning of mathematical methods. [Example]
Main.java
import java.lang.Math;
class Main {
public static void main(String[] args) {
int max = Math.max(3, 5); //Math is a class that is loaded from the outside
System.out.println("The maximum number is" + max);
}
}
In the above case, the max method (the method that returns the larger of the two numbers passed to the argument) is used, so the result is a large number "maximum number is 5". There is also a round method that rounds off the argument after the decimal point and returns it.
I used import java.lang.Math; earlier, but it will be loaded automatically without importing. Besides, all external libraries with "java.lang.class name" are automatically loaded.
Recommended Posts