Java interview questions briefly describe the usage of static and final?

1. Static: modify attributes, methods, code blocks

  • Static property: It can also be called a class variable. It needs to use the class name. Property name to access. The common class variable domain object has nothing to do with the class.

Note: The instance variables in the class are initialized when the object is created. The attributes modified by static, that is, class variables, are actually created and initialized when the class is loaded. The process of class loading is only performed once, that is, the class variables only Will be created once.

  • Static method: class name. method name, direct access.

Note: static modified methods cannot directly access the non-static members (including methods and properties) of this class. Non-static methods of this class can access the static members of this class (including methods and properties), and can call static method.

2. Final: modify variables, methods, and classes

  • Modified variables: The member variables modified by final are constants (constant names are usually capitalized), and cannot be changed once assigned
    • Modify local variables:
      • Modification of basic types: the value of the variable cannot be changed
      • Decorated references: references can only point to fixed objects
    • Modified instance variable: the default value is not effective, you can assign a value
  • Modification method: cannot be overridden by subclasses
  • Modified class: cannot be inherited

All methods in the final class are final by default.

Note: final cannot be used to modify the construction method.

Guess you like

Origin blog.csdn.net/weixin_44296929/article/details/108318190