Use "new class name ()" to instantiate a class. [Example]
class Main {
public static void main(String[] args) {
new Person(); //Person(This time people)Create an instance of the class
}
}
Person.java
class Person{
}
To assign an instance to a variable, use "class type variable name = new class name ()". When assigning an instance, specify the class type, and the class name becomes the class type as it is. [Example]
class Main {
public static void main(String[] args) {
Person person = new Person();
}
}
Person.java
class Person{
}
The instance method uses "public return type method name ()".
Main.java
class Main {
public static void main(String[] args) {
Person person = new Person(); //void is the return type
person.hello();
}
}
Person.java
class Person {
public void hello() {
System.out.println("Good morning");
}
}
For the instance field definition, add public before the variable definition, such as "public data type variable name". [Example]
Person.java
class Person {
public String name;
}
String name defines the definition to put the name. For the instance field, use "instance name.field name". [Example]
Main.java
~abridgement~
Person person = new Person();
person.name("Sato");
System.out.println(person.name); //person.Getting the value of name with name
~abridgement~
[Example]
Main.java
class Main {
public static void main(String[] args) {
Person person = new Person();
person.hello();
person.name = "Sato";
System.out.println(person.name);
}
}
Person.java
class Person {
public String name;
public void hello() {
System.out.println("Good morning");
}
}
this Use the "this" variable to access the instance field in the method. this can only be used in method definitions within a class. This is replaced with the instance calling the method when it is called. [Example]
Main.java
class Main {
public static void main(String[] args) {
Person person = new Person();
person.hello(); //person calls this
person.name = "Sato";
System.out.println(person.name);
}
}
Person.java
class Person {
public String name;
public void hello() {
System.out.println("Good morning" + this.name); //this.(This time)name field of hello method
}
}
Recommended Posts