Organized memo in the head (Java --instance edition)
My Java environment
static
static
fields can be used without instantiating
- Use with
class name.field name
or instance name.field name
after instance creation
- You cannot access non-static
fields or methods from
static methods (only
staticfields or methods can be accessed from
static` methods)
- You can access
static
fields and methods from methods that are not static
Method return value
- The return value of a method must be of the same type as the
return value
or a compatible type
.
Variadic argument
- An argument whose number of arguments can be changed freely. Replaced by an array by the JVM.
- Declare the argument type with three periods
...
immediately after it.
public static void main(String... args) {
//processing
}
- Variadic argument must be the last argument.
public void method(String value, String... args) { } // OK
public void method(String... args, String value) { } // NG
Method overload
- Same method name, different arguments (number, type, order of arguments)
constructor
- Make the method name the same as the class name
- Return value cannot be described
- Can only be called when
new
is done, cannot be called
- Any access modifier is OK
Constructor and initializer {}
The initializer {}
is described directly under the class block. Executed before the constructor is executed.
public class Test {
{
//Initialization process
}
}
There is also a static
initializer. Executed when the class is loaded.
public class Test {
static {
//Initialization process
}
}
- The default constructor is added if no constructor is defined.
- Use
this (...)
when calling another overloaded constructor from a constructor, but when using it, you need to write it at the very beginning of the process.
Modifier
- public: accessible from all classes
- protected: accessible from the same package and inherited subclasses
- (None): Accessable from classes in the same package
- private: Only accessible from within the class
Method arguments
- If a primitive type is specified as a method argument, a copy is passed to the method (changes in the method do not affect the caller's value).
- If the object type is specified as an argument of the method, the instance reference (link) is passed to the method. (If the value changes in the method, so does the caller's value.)