Summarize some of the confusing parts of learning Java. I'm referring to Progate.
The instance method is the "behavior" that the instance has and the instance has.
public <Return type> <Method name>(){
<The contents of the method>
}
Write like.
/*Create an instance of Person class, person1*/
Person person1 = new Person();
/*Call the hello method*/
person1.hello();
Call like.
The instance field is a variable that stores the information that the instance has.
class Person {
/*Declare the type because it is a variable*/
public String name;
}
/*Create an instance*/
Person person1 = new Person();
/*Set a value for name*/
person1.name = "Suzuki";
/*Get the value of name*/
System.out.println(person1.name);
You can access it like this.
A method that belongs to a class.
class Person {
public static <Return type> <Method name>() {
<The contents of the method>
}
}
static
is added.<name of the class>.<Method name>();
Call it like this.
The public static void <method> () {}
seen from the parent's face is actually a class method.
Fields that belong to the class. A variable that stores the information that the class has.
class Person {
public static <Data type> <Variable name>;
}
static
Main.java
class Main {
public static void main(String[] args) {
System.out.println("total" + Person.count + "Is a person");
Person person1 = new Person( ... );
System.out.println("total" + Person.count + "Is a person");
}
}
Person.java
class Person {
/*Store information about the number of people in a variable called count*/
public static int count = 0;
.........
Person(String firstName, ...) {
Person.count ++;
}
}
python
>0 people in total
>1 person in total
count
.A method that is automatically called after creating an instance with new
.
Note that the definition method is fixed
python
class Person {
public String name;
Person() {
/*What you want to do when creating an instance*/
}
}
The constructor is the part of Person () {}
.
It is similar in writing and declaring a method.
However, unlike the method, there is no return value and no void is required.
Because the return value of the constructor is always an instance of that class,
The compiler will tell you even if you don't specify it.
Below is an example of a compiler.
Person.java
class Person {
public String name;
Person(String name) {
this.name = name;
}
}
Main.java
Person person = new Person("Suzuki");
System.out.println(person.name);
Modifier | static | Data type | Method name or field variable name | Method name | |
---|---|---|---|---|---|
Instance method | public | - | Data type | Method name | |
Instance field | public | - | Data type | Variable name of the field | |
Class method | public | static | Data type | Method name | |
Class field | public | static | Data type | Variable name of the field | |
constructor | public | - | Data type | Variable name | name of the class |
It's easy to get confused! that's all!
Recommended Posts