Java basic learning day46 (permission modifiers, code blocks)

1. Permission modifiers

  • Divided into access modifiers and non-access modifiers

2. Access Modifiers

  • Used to control the scope in which a member can be accessed
  • Can modify member variables, methods, constructors, inner classes

3. Classification of access modifiers

  • There are four kinds of scopes, from small to large (private<empty do not write/default<protected<public)
  • As shown in the picture:
    insert image description here
  • In actual development, generally only private and public are used
    a. Member variables are private

b. Method disclosure

c. Special case: If the code of a method is to extract the common code in other methods, and this method does not want to be used by the outside world, then this method is generally private

4. Code blocks

  • In the code, a pair of curly braces is added separately, which is called a code block. As shown in the picture:
    insert image description here
  • According to the location of the code block, it is divided into:
    a. Local code block: the code block is in the method and used to end the scope of the variable in advance. But it has been eliminated at present, and now the computer has a large memory space, there is no need to write local code blocks for several variables.

b. Construction code block: the code is in the member position, which is used to extract the repeated code in multiple construction methods, and when creating an object of this class, the construction code block will be executed first and then the construction method, which is better than the execution of the construction method . But it is also eliminated, not flexible enough, the following two ways can be replaced:
insert image description here

c. Static code block: On the basis of constructing the code block, add the static keyword before {. It is loaded with the loading of the class, and is automatically triggered, and only executed once, as shown in the figure:
Usage scenario: When the class is loaded, do some data initialization, and only initialize once (if you don’t use static code blocks, write them directly in the method) , the code is executed every time the method is called, which is not as expected)
insert image description here

5. Non-access modifiers

  • static modifier: used to modify member methods and member variables
  • final modifier: used to modify classes, methods, variables
  • abstract modifier: used to modify abstract classes and abstract methods
  • final can modify local variables, access modifiers cannot modify local variables, and static cannot modify local variables

Guess you like

Origin blog.csdn.net/u011453680/article/details/129287486