Here are some things to keep in mind when using class methods with instance variables and method methods.
Class methods are primarily responsible for accessing class variables. You must add the static qualifier when declaring it. When calling, use the class name as follows.
(name of the class).(Class method name)
The following description is quoted from Oracle's The Java TM </ sup> Tutorials.
- Instance methods have direct access to class variables and class methods
- Class methods have direct access to class variables and class methods
- Class methods do not have direct access to instance variables and methods ***. You need to refer to the object to access it. Also, the this keyword cannot be used because there is no object indicated by this keyword.
The above "directly accessible" means that you can call only the variable name or only the method name in the processing inside the method.
Here is an example of calling an instance method in a class method.
The class method to be used is main, and the instance method is display. main directly accesses the string type class variable and displays the contents of the string on the console. display displays an integer argument on the console.
Test.java
public class Test{
public static String str = "The class variable was called"; //Class variables
public static void main(String[] args){ //Class method
System.out.println(str); //Direct access to class variables
Test test = new Test(); //Generate Test type object
test.display(5); //Browse Test type object to access instance method
}
public void display(int num){ //Instance method
System.out.println("The numbers are" + num + "is");
}
}
When you run Test.java
The class variable was called
The number is 5
have become.
main is a class method because it has a static modifier. display is an instance method because it doesn't have a static modifier. Therefore, to access display from main, you need to refer to the Test type object. It feels strange to need an object reference when using methods of the same class ...
In this article, we've looked at mutual access between class and instance methods, rather than how to use the class methods themselves.
As a result, I had to be a little careful when calling an instance method inside a class method within the same class.
Then I introduced an example of simple code that directly accesses a class variable within a class method and calls an instance method.
Recommended Posts