Modifiers and keywords

Basic introduction to access modifier

java introduces four access control modifier control methods and properties (member variables)

Access rights (SCOPE):

1. Publicity level: decorated with public, open to the public

2. Protected level: modified with protected and exposed to subclasses and classes in the same package

3. Default level: there is no modifier (default), which is exposed to classes in the same package

4. Private level: private decoration. Only the class itself can be accessed

Static variable (class variable static)

Static variables, also known as class variables, are variables shared by all objects of this class. When any object of this class accesses it

, the same value is obtained. Similarly, when any object area of this class modifies it, the same variable is modified

grammar
Access modifier  static Data type variable name;[Main push]
static Access modifier data type variable name;
Methods to access class variables

Class name Class variable name or object name Class variable name (access permission and scope of access modifier of static variable)

(same as normal attributes)

public class VisitStatic {
    public static void main(String[] args) {
        //Class name Class variable name
        //Note: class variables are created by class loading, so they can be accessed without creating object instantiation
        System.out.println(A.name);
        A a = new A();
        //Object name access
        System.out.println("a.name"+" "+a.name);
    }
}
class A{
    //Class variable
    //The access of class variables must comply with the relevant access permissions
    public static String name = "java program";
    //Common attribute / common member variable / non static attribute / non static member variable
    private int num = 10;
}
matters needing attention

1. When do I need class variables

When we need to make all objects of a class share a variable, we can use class variables (static variables)

2. The difference between class variable and instance variable (common attribute)

Class variables are shared by all objects of the class, while instance variables are exclusive to each object.

3. Adding static is called class variable or static variable, otherwise it is called instance variable / ordinary variable / non static variable

4. Class variables can be defined by class name Class variable name or object name Class variable name to access

(access to class variables must comply with relevant access permissions).

5. Instance variables cannot pass the class name Class variable name access

6. Class variables are initialized when the class is loaded. Even if you do not create an object, as long as the class is loaded,

You can use class variables

7. The life cycle of class variables starts with the loading of the class and is destroyed with the extinction of the class

Static method (class method static)

Static methods, also known as class methods, are methods shared by all objects of the class. When any object of the class accesses it

, the same values are obtained. Similarly, when any object area of this class modifies it, the same method is modified

grammar
Access modifier  static Data return type method name(){}
static Access modifier data return type method name(){}
Class method call

Class name Class method name or object name Class method name (the criterion is to meet the access permission and scope of the access modifier)

Tuition exercise
public class StaticMethod {
    public static void main(String[] args) {
        Stu tom = new Stu("tom");
        Stu.payFee(100);

        Stu jack = new Stu("jack");
        jack.payFee(200);

        //Output total tuition
        Stu.showFee();
    }
}
class Stu{
    private String name;//Ordinary member
    //Define static variables to accumulate students' tuition fees
    private static double fee = 0;

    public Stu(String name) {
        this.name = name;
    }
    //Static method
    //Static methods can access static properties
    public static void payFee(double fee){
        Stu.fee += fee;//Accumulated to
    }
    public static void showFee(){
        System.out.println("School received"+"Total tuition"+" "+Stu.fee);
    }
}
Class method usage scenario

When the method does not involve any object related members, the method can be designed as a static method to improve the development efficiency

To be precise, it is to design the general methods into static methods, so that they can be used without creating objects

Method utils Math class and Collections collection class in tool class

Each tool class has a static method, which can be used directly to the class The method name () can be used

Development tools

When developing your own tool class, you can make the method static and easy to call

class MyTools{
    //Find the sum of two numbers
    public static double sum(double n1,double n2){
        return n1 + n2;
    }
}
public class StaticMethod {
    public static void main(String[] args) {
   		//Call summation method
        System.out.println(MyTools.sum(12,20));
    }
}
matters needing attention

1. Class methods and ordinary methods are loaded with the loading of classes, and the structure information is stored in the method area

There is no this parameter in class methods, and the parameter of this is implicit in ordinary methods

2. Class methods can be called by class name or object name

3. Ordinary methods are related to objects and need to be called through object names, such as object names Method name (parameter), cannot pass class name

Call.

4. Object related keywords, such as this and super, are not allowed in class methods. Common methods (member methods) can.

5. Class methods (static methods) can only access static variables or static methods. (access rights must be observed)

6. Ordinary member method can access ordinary variables (Methods), static members and non static members (access permission must be observed)

practice
public class Excerse1 {
    public static void main(String[] args) {
        new Test().count();
        new Test().count();
        System.out.println(Test.count);
    }
}
class Test{
    static int count = 8;
    public void count(){
        System.out.println("count = "+(count++));
    }
}
public class Excerse2 {
    public static void main(String[] args) {
        System.out.println("Number olf total is "+Person.getTotalPerson());
        Person p1 = new Person();
        System.out.println("Number olf total is "+Person.getTotalPerson());
    }
}
class Person{
    private int id;
    private static int total = 0;

    public static int getTotalPerson() {
        return total;
    }

    public Person() { //constructor 
        total++;   //total = 1
        id = total;  //id = 1
    }
}

Code block

Basic introduction

Coded blocks, also known as initialization blocks, are members of a class [part of a class]. Similar to methods, logical statements are encapsulated in the method body and surrounded by {}.

But unlike methods, there are no method names, no returns, no parameters, only method bodies, and they are not displayed through objects or classes

Instead, it is called implicitly when the class is loaded or when an object is created.

grammar
[Modifier ]{code}

be careful:

1. The modifier is optional, and only static can be written

2. Code blocks are divided into two categories. Those modified with static are called static code blocks, and those without static modification are called ordinary code blocks.

3. The code can be any logical statement (input, output, method call, loop, judgment, etc.)

Benefits of code blocks

1. It is equivalent to another form of constructor (supplementary mechanism to the constructor), which can be initialized

2. Scenario: if there are repeated statements in multiple constructors, they can be extracted into the initialization block,

Improve code reusability (code blocks take precedence over constructor calls)

public class Codestatic {
    public static void main(String[] args) {
        move move1 = new move("Left ear");
        move move2 = new move("Iron Man",56);
        move move3 = new move("Spider-Man",200,"End of viewing");

    }
}
class move{
    private String name;
    private  double price;
    private String director;
    
    //The code block takes precedence over the constructor, and the code block is called first
    {
        System.out.println("I open the movie interface");
        System.out.println("Ticket Price");
        System.out.println("The movie is over");
    }
    public move(String name) {
        System.out.println("1 Called");
        this.name = name;
    }

    public move(String name, double price) {
        System.out.println("2 Called");
        this.name = name;
        this.price = price;
    }

    public move(String name, double price, String director) {
        System.out.println("3 Called");
        this.name = name;
        this.price = price;
        this.director = director;
    }
}
Precautions and details for use

1.static code block is also called static code block. Its function is to initialize the class. It will follow the loading of the class

And execution will only be executed once. Ordinary code blocks are executed every time an object is created.

Static initialization block takes precedence over normal initialization block.

2. The class will be in [when creating object instance (new)], [when creating sub class object instance, the parent class will also be loaded]

[when using static members of a class (static properties, static methods)] is loaded.

3. Ordinary code blocks will be implicitly called when creating object instances.

Once created, it will be called once.

If you only use static members of a class, ordinary code blocks do not execute

4. When creating an object, the calling sequence of a class is:

​ (1). Call static code block and static attribute initialization (Note: static code block and static attribute initialization call have the same priority

, if multiple static code blocks and static variables are initialized, they are called in the order they define)

​ (2). Call the initialization of ordinary code block and ordinary attribute (Note: initialization of ordinary code block and ordinary attribute)

The priority of the call is the same. If there are multiple ordinary code blocks and multiple ordinary attributes to initialize, the

Define sequence (call)

​ (3). Call construction method

5. The front of the constructor actually implies a super() and calling a common code block,

Statically related code blocks and attribute initialization are executed when loading,

Therefore, it takes precedence over the execution of constructors and ordinary code blocks

6. When creating a subclass, their static code block, static attribute initialization, ordinary code block,

The normal attribute is initialized, and the calling sequence of the construction method is as follows:

(1) static code blocks and static attributes of the parent class (the priority is the same and executed in the order of definition)

(2) static code blocks and static attributes of subclasses (with the same priority and executed in the order of definition)

(3) initialization of common code blocks and common attributes of the parent class (with the same priority and in the order of definition)

(4) construction method of parent class

(5) initialization of common code blocks and common attributes of subclasses (with the same priority and in the order of definition)

(6) construction method of subclass

7. Static code blocks can only call static members (static attributes and static methods) directly. Normal

A code block can call any member

final keyword

Basic introduction

Final means final in Chinese

final can modify classes, properties, methods, and local variables

Usage scenario

1. When you do not want the class to be inherited, you can use the final modifier

2. When you don't want a method of the parent class to be overridden by a subclass, you can modify it with the final keyword

3. When you do not want the value of an attribute of a class to be modified, you can use final to modify it.

4. When you do not want a local variable to be modified, you can use the final modifier

Precautions and details

1. The attribute modified by final is also called constant;

2. When defining the final modified attribute, it must be assigned an initial value, and it cannot be modified or assigned in the future

You can set an initial value at one of the following locations

​ 1). When defining: for example, public final double Taxdes = 0.08;

​ 2). In the constructor

3) in code block

3. If the final modified attribute is static, the initialization position can only be

​ 1). Definition 2) A static code block cannot be assigned in a constructor.

4.final class cannot inherit, but it can instantiate objects

5. If the class is not final but contains a final method, the method cannot be overridden,

But it can be inherited

6. If a class is already final, there is no need to modify the method to final

7.final cannot modify the constructor (constructor)

8.final and static are often used together, which is more efficient and will not lead to class loading (for static aspects). The underlying compilation is optimized

9. Packing class (Integer, Double, Float, Boolean, etc. are all final),

String is also the final class

practice
public class Circle {
    /**
     * Calculate the area of a circle
     * PI 3.14*/
    public static void main(String[] args) {
        Gongshi gongshi = new Gongshi(5.00);
        System.out.println(gongshi.Circlesu());
    }
}
class Gongshi{
    private double radius;
    private final  double PI;

    public Gongshi(double radius) {
        this.radius = radius;
        PI = 3.14;
    }
    public double Circlesu(){
        return PI * radius * radius;
    }
}

Added by The Swedish Tower on Tue, 01 Feb 2022 15:20:55 +0200