Thank you. Below, I will write an article for my memo.
First, create Main.java for the main process
Main.java
class Main {
public static void main(String[] args) {
//Instance creation and assignment to variables
Sample sample = new Sample();
System.out.println("【sample】");
System.out.println("name:" + sample.name);
}
}
Next, create Sample.java that calls the constructor
Sample.java
class Sample {
//Definition of constants
public String name;
//Constructor definition
Sample() {
this.name = "Let's go";
}
}
On the 4th line of Main.java
Sample sample = new Sample();
Execute the constructor of Sample.java (lines 6-8 of Sample.java).
Then on line 6 of Main.java
System.out.println("name:" + sample.name);
In this process, it was set by the constructor of Sample.java
Outputs the name (with "Let's" set in the contents) to the console of the processing result.
The result of compiling and running the two java files is ...
【sample】
Name: Let's go
It will be.
I feel like I was able to call the sample.java constant as private ... Please point out if there is any better way to write it.
Excuse me.
Recommended Posts