-Does the class itself have it? Disclosure range?
――Aside from "when to use" --All classes are fixed as public --Miscellaneous
This is the simplest form Java has qualifiers in the main method, which makes it difficult to get started.
Calculator.java
package jbasic;
public class Calculator {
int add(int number1, int number2) {
int result = number1 + number2;
return result;
}
}
An instance of the class in which the method is written has been created | The class in which the method is written has not been instantiated | |
---|---|---|
Same package | ○ | × |
Package is different | × | × |
Seller.java
package jbasic; //Same package
public class Seller {
public static void main(String[] args) {
Calculator calc = new Calculator(); //Instance generation
System.out.println(calc.add(10,5)); //OK!
}
}
Seller2.java
package jbasic; //Same package
public class Seller2 {
public static void main(String[] args) {
//No instantiation
System.out.println(Calculator.add(10,5)); //Get angry at not statically referencing non-static methods
}
}
With this, you can hit the method without instantiating it.
Calculator.java
package jbasic;
public class Calculator {
static int add(int number1, int number2) {
int result = number1 + number2;
return result;
}
}
An instance of the class in which the method is written has been created | The class in which the method is written has not been instantiated | |
---|---|---|
Same package | ○ | ○ |
Package is different | × | × |
Seller2.java
package jbasic; //Same package
public class Seller2 {
public static void main(String[] args) {
//No instantiation
System.out.println(Calculator.add(10,5)); //OK!
}
}
Robot.java
package jmaster; //Different package
public class Robot {
public static void main(String[] args) {
System.out.println(Calculator.add(10,5)); //Get angry to make the class public
}
}
If you add public, you can use the method from the class of other packages.
Calculator.java
package jbasic;
public class Calculator {
public static int add(int number1, int number2) {
int result = number1 + number2;
return result;
}
}
An instance of the class in which the method is written has been created | The class in which the method is written has not been instantiated | |
---|---|---|
Same package | ○ | ○ |
Package is different | ○ | ○ |
Robot.java
package jmaster; //Different package
import jbasic.Calculator; //Class import required
public class Robot {
public static void main(String[] args) {
System.out.println(Calculator.add(10,5)); //OK!
}
}
--Static method cannot use instance field --If it is public, it may be used strangely and it may be a problem (I understand, but I do not understand the actual harmful effects)
Recommended Posts