I don't refer to class slides, so I think it's explained from a different perspective. Maybe I'm saying it (should).
Please let me know if you may make a mistake because it is an ad lib!
Part.1 Try to instantiate it ← Imakoko Part.2 Cleaner with constructor Part.3 Let's control the access and limit the incoming value Part.4 Try using class variables / methods
A class is a collection of fields and methods, often referred to as a blueprint </ b>.
When using a field variable written in a class or a method, a instance </ b> is often created and used. I think it's likened to a blueprint because an instance is created based on a blueprint called a class.
I don't feel right at all.
Instances are made from classes, so don't overwhelm them with the previous explanation.
Instances are created with the new
keyword, and variables and methods can be operated independently.
I want you to swallow one setting. Let's prepare a class with the theme of digital student ID and generate an instance of it.
The student ID class Digital Student Card
created here has a student ID number num
and a student name name
in the field.
class DigitalStudentCard{
//Student number
int num;
//name
String name;
//Method for output (introduce yourself)
String getSelfIntroduction(){
return "Student number: " + num + "name: " + name);
}
}
Let's use this class.
class UseClass{
public static void main(String[] args){
//Instance generation
DigitalStudentCardtanaka tanaka = new DigitalStudentCard();
//Assign to instance variable
tanaka.num = 118114;
tanaka.name = "Kakuei Tanaka";
//Create another instance
DigitalStudentCardnoguchi noguchi = new DigitalStudentCard();
//Assign to the variable of the newly created instance
noguchi.num = 118514;
noguchi.name = "Hideyo Noguchi";
//output
System.out.println(tanaka.getSelfIntroduction);
//Student number:118114 Name:Kakuei Tanaka
System.out.println(noguchi.getSelfIntroduction);
//Student number:118514 Name:Hideyo Noguchi
}
}
Roughly, I issued a student ID card for Kakuei Tanaka and Hideyo Noguchi. By doing this, I think it will be easier to understand that multiple variables are connected and related.
This would create tanakaName
and noguchiName
and mess up the code if you didn't use the class ...
It's horrifying.
Like this, many of the features I'm about to explain are to make the code easier to read, cleaner, and simpler </ b>. The more you use it, the easier it will be to write code, so let's remember it more and more.
The tanaka
and noguchi
that I made earlier are the same human beings as Kakuei Tanaka and Hideyo Noguchi, but they are treated as different </ b> as if they were different people.
When compared with a logical formula, it looks like this.
if(tanaka == noguchi){
System.out.println("Same instance");
}else{
System.out.println("Different instance");
}
/*Execution result*/
// >>Different instance
Next, let's implement the constructor! Next → Part.2 Cleaner with constructor