Yesterday about three terms I wrote, but today about the actual usage I will write.
To check the basic usage of the class, create a program with the following contents.
Inside the "{" and "}" that define the class That is, it is described in curly braces And it is a variable described outside the method. Also called an instance variable.
Member variables
void nowTime(){
System.out.println("Current" + time + "is");
}
TestClass.java
class TestClass {
//Member variables
public String name = "Samurai";
//Method
public String testMethod(){
return "Engineer";
}
}
Main.java
public class Main {
public static void main(String[] args) {
//Create an object of class
TestClass c = new TestClass();
//Refer to member variables
String str1 = c.name;
//Method call
String str2 = c.testMethod();
//Output result
System.out.println(str1 + str2);
}
}
as a result
Output result
> javac Main.java
> java Main
SamuraiEngineer
Basic flow To explain in detail
TestClass.java
//① Set member variables
public String name = "Samurai";
//
TestClass.java
//(2) Define the method and return Enginerr.
public String testMethod(){
return "Engineer";
}
}
Main.java
//③TestClass.Create class object from java
TestClass c = new TestClass();
Main.java
//(4) Refer to the member variable, which is set in (2).
String str1 = c.name;
Main.java
//⑤ Call the method of ② that has been set
String str2 = c.testMethod();
Main.java
//(6) Outputs the result set in the variable.
System.out.println(str1 + str2);
Recommended Posts