Java modifiers fall into two main categories:
- Access modifiers
- Non-access modifiers
Non-access modifier java static
- Static is a modifier, a static-decorated member variable and a member method that does not depend on a particular instance of a class and is shared by all instances of the class, so a static class method cannot be used to define keywords such as this,super.
- Static member variables and methods can be called directly using the class, as follows to access Name,age,printinfo () directly using the Dog.
- Static methods can only access static members, non-static methods can access both static and non-static members, as in the Printinfo () method using the static adornment, which involves the name and age must also use the static adornment.
public class Dog { static String name; static int age; public static void printInfo() { System.out.println("name:" + name + ", age:" + age); } public static void main(String[] args) { Dog.name = "roy"; Dog.age = 3; Dog.printInfo(); Dog dog = new Dog(); dog.printInfo(); }}
name:roy, age:3name:roy, age:3
Java final
- Final can be decorated with classes, methods, variables (member variables and local variables)
- When final modifies a class, it means that the class cannot be inherited
- When final modifies a method that explicitly prohibits the method from being overwritten in subclasses
- When final modifies a variable, such as the base type, to indicate that the value is determined, cannot be modified, and, if the reference type, cannot point to another object after initialization
Access modifiers
- Public, visible to all classes
- Protected, visible to classes and subclasses within the same package
- Default, a class within the same package is visible
- Private, visible to the current class
modifier |
Current Class |
in the same package |
descendant class |
Other Packages |
Public |
Y |
Y |
Y |
Y |
Protected |
Y |
Y |
Y |
N |
Default |
Y |
Y |
N |
N |
Private |
Y |
N |
N |
N |
The Java static and final