15_ The most comprehensive Java object-oriented explanation_ Class members: properties, methods, constructors

1, One of the members of the class: properties

Syntax format of attribute

Modifier data type attribute name = initialization value;  

Member variables, also known as instance variables, refer to the state of an object.
Member variables are defined in the class and can be accessed throughout the class.
Member variables are created with the creation of the object and exist in the heap memory where the object is located.
Member variables have default initialization values.

explain:

Modifier:
Common permission modifiers include: private, default, protected, and public
Other modifiers: static, final (not considered temporarily)
    
Data type:
Any basic data type (such as int, Boolean) or any reference data type.
    
Property name:
It belongs to the identifier, which can comply with the naming rules and specifications.

give an example:

public class Person {
    private int age;  // Declare the private variable age
    public String name;    // Declare public variable name
    public String[] hobby; // Declare variables of array type
}

On the classification of variables

Classification of variables: member variables and local variables;
Outside the method, variables declared in the class are called member variables. Variables declared inside a method body or code block are called local variables.

Note: similarities and differences in initialization values between the two:
Same: all have a life cycle; All need to be declared before use;
Exception: local variables, except formal parameters, need to be explicitly initialized.

Memory location of member variable vs local variable

class Person {//human beings
    // 1. Properties
    String name;// full name
    int age = 1;// Age
    boolean isMale;// Is it male

    public void show(String nation) { // nation parameter: local variable
        String color;// color: local variable
        color = "yellow";
    }
}

//Test class
class PersonTest {
    public static void main(String[] args) {
        Person p = new Person();
        p.show("USA");
    }
}

Default initialization assignment of object properties

When an object is created, it will automatically initialize and assign various types of member variables. All variable types except the basic data type are reference types, such as the Person above and the array mentioned earlier.

2, Class member 2: method

What is a method (method, function):
In order to solve the problem of repeated code writing, you can extract the code that needs to be repeated and put it in a {} (code block), give this code a name, and call this code through this name to achieve what you want to do. The extracted code can form a method.

A method is an abstraction of the behavior characteristics of a class or object, which is used to complete a function operation. Also called a function or procedure in some languages.
The purpose of encapsulating functions into methods is to realize code reuse and simplify code
Methods in Java cannot exist independently. All methods must be defined in classes.

Significance of the method:
                1. Improve code reusability.
                2. Enhance code maintainability.

Example code:

public class Person {
    private int age;

    public int getAge() { //Declare method getAge()
        return age;
    }

    public void setAge(int i) { //Declare method setAge
        age = i; //Assign the value of parameter i to the member variable age of the class
    }
}

Method declaration format

Member methods, also known as instance methods, refer to the behavior of objects.
Methods can also be called functions.
The function of program is embodied in method, which is the basic component of object function.

Modifier return value type method name (parameter type parameter 1, parameter type parameter 2,...) {
Method body program code
Return return value;
        }

explain:

	Modifier:
		public default protected private etc.

    Return value type:
		If the method does not return a value, the void To show. In general, there is no need to use in methods that have no return value return.However, if used, only“ return;"Means to end this method.
		If a method has a return value, the type of the return value must be specified when the method is declared. At the same time, in the method, you need to use return Keyword to return a variable or constant of the specified type:“ return Data.
		When the return value type of a method is uncertain, the return value type can be written as Object(because Object yes java Can receive any type of return value)[Don't usually do this]. If there are branches, all branches must have feedback;
		Do we define whether a method should have a return value?
			① Title Requirements
			② Based on experience: specific analysis of specific problems

    Method name:
		It belongs to the identifier, and the naming rules and specifications of the identifier shall be followed when naming, "see the meaning of the name".
	
	Parameter list:
		It can contain zero, one or more parameters. When there are multiple parameters, the middle is used“,"separate.
    	Parameter type: the data type of data passed in when calling a method. Parameter types include basic data type and reference data type.
		Parameter name: the name of the parameter passed in when calling the method.
		When we define methods, should we define formal parameters?
			① Title Requirements
			② Based on experience: specific analysis of specific problems

    Method body:
		Code to realize business functions.
	
	return Keyword usage: the data returned to the calling program after the method is executed.
		Scope of use: used in the method body
        Function: end method and return value.
            ① End method ② For methods with return value types, use"return data"Method returns the desired data.
			Note: return You cannot declare an execution statement after a keyword.

    matters needing attention:
		After the method definition is completed,The method will be executed only when the method is called, and will not be executed when it is not called.
		Method, you can call the properties or methods of the current class.
		Special: method A Method called again in A:Recursive method.
		Method cannot be defined.

Three elements of method

Method consists of three elements: return value type, method name and parameter list

    1,Methods without parameters and return values
        void say(){
            System.out.println("Hello World!!!");
        }

    2,Method with parameters and no return value
        void fun2(int num){
            System.out.println(num);
        }

    3,Method with return value and no parameters
        int fun3(){
            return 100;
        }

    4,Methods with parameters and return values.
        int fun4(int num){
            return num;
        }

    5,Write a method to calculate the subscript of the maximum value of the array.
        int getMax(int[] arr){
            if(arr == null){
                return -1;
            }
            int maxValue = arr[0];
            int index = 0;
            for(int i = 0; i < arr.length; i++){
                if(arr[i]>maxValue){
                maxValue = arr[i];
                index = i;
                }
            }
            return index;
        }


        int getMax(double[] arr){
            if(arr == null){
                return -1;
            }
            int maxValue = arr[0];
            int index = 0;
            for(int i = 0; i < arr.length; i++){
                if(arr[i]>maxValue){
                maxValue = arr[i];
                index = i;
                }
            }
            return index;
        }

Classification of methods

Method classification: according to whether there are formal parameters and return values.

Method call

Method is called by method name, and only the called method will execute.

Process analysis of method call

Principle and procedure of method call

First write a java class.
Find the main method in the java class and call the main method.
Call the getArea method in the main method.
Let formal parameters receive arguments.
Execute the business code inside the getArea method.
The variables inside the method are destroyed at the end of the method. Finally, the return value needs to be returned outside the method through return.
End.

be careful

Method is called once and executed once.
If there is no specific return value and the return value type is represented by the keyword void, the return statement may not be used in the method body. If used, it is only used to end the method.
When defining a method, the result of the method should be returned to the caller for processing.
Methods can only call methods or properties, and methods cannot be defined inside methods.

Method exercises

1. Create a Person class, which is defined as follows:
(1) create an object of the Person class, set the name, age and sex properties of the object, call the study method, output the string "studying", call the showAge() method to display the age value, and call the addAge() method to increase the age property value of the object by 2 years.
(2) create a second object, perform the above operations, and experience the relationship between different objects of the same class.
(3) analyze the memory storage model by drawing.

 

public class Person {

    String name;
    int age;
    /**
     * sex:1 Indicates that it is male
     * sex:0 Indicates that it is female
     */
    int sex;

    public void study() {
        System.out.println("studying");
    }

    public void showAge() {
        System.out.println("age:" + age);
    }

    public int addAge(int i) {
        age += i;
        return age;
    }
}

public class PersonTest {
    public static void main(String[] args) {
        Person p1 = new Person();

        p1.name = "Tom";
        p1.age = 18;
        p1.sex = 1;

        p1.study();
        p1.showAge();

        int newAge = p1.addAge(2);
        System.out.println(p1.name + "The new age is:" + newAge);
        System.out.println(p1.age);//20

        System.out.println("----------------------------");
        Person p2 = new Person();
        p2.showAge();//0
        p2.addAge(10);
        p2.showAge();//10

        p1.showAge();

    }
}

2. Using the object-oriented programming method, the class Circle is designed to calculate the area of the Circle.

//Test class
public class CircleTest {
    public static void main(String[] args) {

        Circle c1 = new Circle();

        c1.radius = 2.1;

        //Corresponding method I:
        //		double area = c1.findArea();
        //		System.out.println(area);

        //Corresponding method 2:
        c1.findArea();


        //bad call
        //		double area = c1.findArea(3.4);
        //		System.out.println(area);

    }
}

//circular
class Circle{

    //attribute
    double radius;

    //Find the area of a circle
    //Mode 1:
    //	public double findArea(){
    //		double area = Math.PI * radius * radius;
    //		return area;
    //	}

    //Mode 2:
    public void findArea(){
        double area = Math.PI * radius * radius;
        System.out.println("Area:" + area);
    }

    //Error condition:
    //	public double findArea(double r){
    //		double area = 3.14 * r * r;
    //		return area;
    //	}
    //	
}

3. Object array question.
Class Student is defined, which contains three attributes: Student number(int), grade state(int), and grade score(int). Create 20 Student objects with Student numbers from 1 to 20. Grades and grades are determined by random numbers.
Question 1: print out the student information of grade 3 (state value is 3).
Question 2: use bubble sorting to sort students' grades and traverse all student letters
        
Tip:
1) generate random number: math Random(), return value type double;  
2) rounding: math Round (double D), return value type long.

public class StudentTest {
    public static void main(String[] args) {

        //Declare an array of Student type
        Student[] stus = new Student[20];  //String[] arr = new String[10];

        for (int i = 0; i < stus.length; i++) {
            //Assign values to array elements
            stus[i] = new Student();
            //Assign a value to the property of the Student object
            stus[i].number = (i + 1);
            //Grade: [1,6]
            stus[i].state = (int) (Math.random() * (6 - 1 + 1) + 1);
            //Score: [0100]
            stus[i].score = (int) (Math.random() * (100 - 0 + 1));
        }

        //Traverse student array
        for (int i = 0; i < stus.length; i++) {
            //			System.out.println(stus[i].number + "," + stus[i].state 
            //					+ "," + stus[i].score);

            System.out.println(stus[i].info());
        }

        System.out.println("********************");

        //Question 1: print out the student information of grade 3 (state value is 3).
        for (int i = 0; i < stus.length; i++) {
            if (stus[i].state == 3) {
                System.out.println(stus[i].info());
            }
        }

        System.out.println("********************");

        //Question 2: use bubble sorting to sort students' grades and traverse all student information
        for (int i = 0; i < stus.length - 1; i++) {
            for (int j = 0; j < stus.length - 1 - i; j++) {
                if (stus[j].score > stus[j + 1].score) {
                    //If you need to change the order, exchange the elements of the array: Student object!!!
                    Student temp = stus[j];
                    stus[j] = stus[j + 1];
                    stus[j + 1] = temp;
                }
            }
        }

        //Traverse student array
        for (int i = 0; i < stus.length; i++) {
            System.out.println(stus[i].info());
        }

    }
}

class Student {
    int number;//Student number
    int state;//grade
    int score;//achievement

    //Method of displaying student information
    public String info() {
        return "Student number:" + number + ",Grade:" + state + ",Achievement:" + score;
    }

}

Memory parsing of object array

4. Custom array tool class
Define the class, and define the methods for calculating the maximum value, minimum value, sum, average score, inversion, copy, sorting, traversal, search, etc;

public class ArrayUtil {

    // Find the maximum value of the array
    public int getMax(int[] arr) {
        int maxValue = arr[0];
        for (int i = 1; i < arr.length; i++) {
            if (maxValue < arr[i]) {
                maxValue = arr[i];
            }
        }
        return maxValue;
    }

    // Find the minimum value of the array
    public int getMin(int[] arr) {
        int minValue = arr[0];
        for (int i = 1; i < arr.length; i++) {
            if (minValue > arr[i]) {
                minValue = arr[i];
            }
        }
        return minValue;
    }

    // Sum arrays
    public int getSum(int[] arr) {

        int sum = 0;
        for (int i = 0; i < arr.length; i++) {
            sum += arr[i];
        }
        return sum;
    }

    // Average the array
    public int getAvg(int[] arr) {

        return getSum(arr) / arr.length;
    }

    // Invert array
    public void reverse(int[] arr) {
        for (int i = 0; i < arr.length / 2; i++) {
            int temp = arr[i];
            arr[i] = arr[arr.length - i - 1];
            arr[arr.length - i - 1] = temp;
        }
    }

    public void reverse(String[] arr) {

    }

    // Copy array
    public int[] copy(int[] arr) {
        int[] arr1 = new int[arr.length];
        for (int i = 0; i < arr1.length; i++) {
            arr1[i] = arr[i];
        }
        return arr1;
    }

    // Array sorting
    public void sort(int[] arr) {
        // Bubble sorting
        for (int i = 0; i < arr.length - 1; i++) {

            for (int j = 0; j < arr.length - 1 - i; j++) {

                if (arr[j] > arr[j + 1]) {
                    int temp = arr[j];
                    arr[j] = arr[j + 1];
                    arr[j + 1] = temp;
                }

            }

        }
    }

    // Traversal array
    public void print(int[] arr) {
        for (int i = 0; i < arr.length; i++) {
            System.out.print(arr[i] + "\t");
        }
        System.out.println();
    }

    // Find the specified element
    public int getIndex(int[] arr, int dest) {
        // Linear search:
        for (int i = 0; i < arr.length; i++) {
            if (dest == arr[i]) {
                return i;
            }
        }

        return -1;//Returns a negative number indicating that it was not found
    }

}

public class ArrayUtilTest {
    public static void main(String[] args) {

        ArrayUtil util = new ArrayUtil();
        int[] arr = new int[]{32, 34, 32, 5, 3, 54, 654, -98, 0, -53, 5};
        int max = util.getMax(arr);
        System.out.println("The maximum value is:" + max);

        System.out.println("Before sorting:");
        util.print(arr);

        util.sort(arr);
        System.out.println("After sorting:");
        util.print(arr);

//		System.out.println("find:");
//		int index = util.getIndex(arr, -5);
//		if(index >= 0){
//			System.out.println("found, index address:" + index ");
//		}else{
//			System.out.println("not found");
//		}


//		util.reverse(arr);
    }
}

Method overloading

    summary:
        In the same class, more than one method with the same name is allowed, as long as their parameter number, parameter type and parameter order are different.
		The significance of method overloading is to reduce the memory burden of developers.

    characteristic:
        It has nothing to do with the permission modifier, return value type, formal parameter variable name and method body of the method.
        Different parameter lists are reflected in different types and numbers of parameters. When the number and type are the same, different order is OK.
        When called, jvm Virtual machines distinguish methods with the same name by different parameter lists.

	Overload example:
        //Returns the sum of two integers
        int add(int x,int y){return x+y;}
        
		//Returns the sum of three integers
        int add(int x,int y,int z){return x+y+z;}
        
		//Returns the sum of two decimals
        double add(double x,double y){return x+y;}

		Arrays Overloaded in class sort() / binarySearch()

	Pithy formula:
		Basis for judging whether it is overloaded:"Two are the same and different"
			Same class and method name
			Different parameter lists: different parameter numbers, different parameter types, and different parameter sequences

	How to determine a specified method when calling a method through an object:	
		Method name ---> parameter list
public class OverLoadTest {
    public static void main(String[] args) {
        OverLoadTest test = new OverLoadTest();
        test.getSum(1, 2);
    }

    //The following four methods constitute overloads
    public void getSum(int i, int j) {
        System.out.println("1");
    }

    public void getSum(double d1, double d2) {
        System.out.println("2");
    }

    public void getSum(String s, int i) {
        System.out.println("3");
    }

    public void getSum(int i, String s) {
        System.out.println("4");
    }

    //The following three methods cannot be overloaded with the above four methods
    //	public int getSum(int i,int j){
    //		return 0;
    //	}

    //	public void getSum(int m,int n){
    //		
    //	}

    //	private void getSum(int i,int j){
    //		
    //	}


}

Code example:

/*
 * Employee category:
 *   Member variables: employee number, name, age, position, Department
 *   Member method: eat, work, sleep
 * */
public class Emp {
    // Member variable
    int empId;
    String empName;
    String age;
    String job;
    String deptName;

    // Member method
    void eat() {
        System.out.println(empName + "Eating behavior");
    }

    /*
     * All employees have work behavior, but it can not be generalized
     *   The same is the behavior of sales work
     *       Some employees can complete their work without any help;
     *       Some employees only need someone's guidance;
     *       Some employees not only need guidance, but also need to invest money to invite customers to dinner;
     * Method overload:
     *   In the same class, more than one method with the same name is allowed, as long as their parameter number, parameter type and parameter order are different.
     *       void work() / work(String name) Different number of parameters
     *       work(String name) / work(double money)  Different parameter types
     *       void work(double money,String name) / work(String name,double money) The order of parameters is different
     * */
    void work() {
        System.out.println("I'm an old driver,It all depends on one mouth,Completely handle the customer!");
    }

    void work(String name) {
        System.out.println("I'm a skilled worker,But I need" + name + "Only with your help can you handle the customer!");
    }

    void work(double money) {
        System.out.println("I'm a skilled worker,But I need" + money + "Yuan takes customers to eat, drink and have fun!");
    }

    void work(double money, String name) {
        System.out.println("I'm a novice,I need it" + money + "Yuan takes customers to eat, drink and have fun,And need" + name + "With your help!");
    }

    void work(String name, double money) {
        System.out.println("I'm a novice,I need it" + money + "Yuan takes customers to eat, drink and have fun,And need" + name + "With your help!");
    }

    void sleep() {
        System.out.println(empName + "Sleep behavior");
    }
}

Using overload method can bring convenience to programming.
For example, system out. Println () method is a typical overloaded method. Its internal declaration form is as follows:
                public void println(byte x)
                public void println(short x)
                public void println(int x)
                public void println(long x)
                public void println(float x)
                public void println(double x)
                public void println(char x)
                public void println(double x)
                public void println()
        ......

Heavy load exercise:

1. Judgment:
Overloaded with void show(int a,char b,double c) {} are:
        a) void show(int x,char y,double z){} // no
        b) int show(int a,double c,char b){} // yes
        c) void show(int a,double c,char b){} // yes
        d) boolean show(int c,char b){} // yes
        e) void show(double c){} // yes
        f) double show(int x,char y,double z){} // no
        g) void shows(){double c} // no

2. Define three overloaded methods max(). The first method calculates the maximum value of two int values, the second method calculates the maximum value of two double values, and the third method calculates the maximum value of three double values, and calls three methods respectively.

public class OverloadExer {

    //1. The following three methods constitute overloading
    public void operation(int i) {
        System.out.println(i * i);

    }

    public void operation(int i, int j) {
        System.out.println(i * j);
    }

    public void operation(String s) {
        System.out.println(s);
    }

    //2. The following three methods constitute overloading
    public int max(int i, int j) {
        return (i > j) ? i : j;
    }

    public double max(double d1, double d2) {
        return (d1 > d2) ? d1 : d2;
    }

    public double max(double d1, double d2, double d3) {
        double max = (d1 > d2) ? d1 : d2;
        return (max > d3) ? max : d3;
    }
}

Variable number of formal parameters

Java se 5.0 provides the Varargs(variable number of arguments) mechanism, which allows you to directly define formal parameters that can match multiple arguments. Thus, you can pass a variable number of arguments in a simpler way.
Before JDK 5.0: array parameters are used to define methods, and multiple variables of the same type are passed in
                public static void test(int a ,String[] books);
JDK 5.0 start: use variable number formal parameters to define methods, and pass in multiple variables of the same type
               public static void test(int a ,String...books);
    
explain:
        1. Declaration format: method name (parameter type name... Parameter name)
        2. When calling a method with variable number of formal parameters, the number of parameters passed in can be: 0, 1 or more
        3. Methods with variable number formal parameters have the same name as those in this class, and methods with different formal parameters constitute overloads
        4. The use of variable parameter methods is consistent with the use of arrays in the method parameter part
        5. The parameter part of the method has deformable parameters, which need to be placed at the end of the formal parameter declaration
        6. At most one variable number parameter can be declared at the parameter position of a method

public class MethodArgsTest {

    public static void main(String[] args) {

        MethodArgsTest test = new MethodArgsTest();
        test.show(12);
        // test.show("hello");
        // test.show("hello","world");
        // test.show();

        test.show(new String[]{"AA", "BB", "CC"});
    }

    public void show(int i) {

    }

    public void show(String s) {
        System.out.println("show(String)");
    }

    public void show(String... strs) {
        System.out.println("show(String ... strs)");

        for (int i = 0; i < strs.length; i++) {
            System.out.println(strs[i]);
        }
    }
    //Cannot exist with the previous method
    //	public void show(String[] strs){
    //		
    //	}

    //The variable argument type String of the method 
    //show must be the last parameter
    //	public void show(String ...strs,int i){
    //		
    //	}

}

Parameter passing mechanism in method

Overview:
Method must be called by its class or object to make sense. When we want to call a method, we will pass the specified data to the parameters in the method, so that the parameters in the method have the specified data. This transfer method is called parameter transfer.

Characteristics of parameter transfer:
When declaring a method, the variables in the parameter list are formal parameters, abbreviated as formal parameters.
When calling a method, the value passed to the method is an actual parameter, which is reduced to an actual parameter.

Classification of parameter transfer:
When the parameter is a basic data type, the "data value" of the argument basic data type variable is passed to the formal parameter, which is referred to as value transfer for short.
When the parameter is a reference data type, the address value of the argument reference data type variable is passed to the formal parameter, which is referred to as reference passing for short.

pass by value

public class ValueTransferTest {
    public static void main(String[] args) {
        int a = 10;
        int b = 20;
        System.out.println("a Value of:" + a + ",b Value of:" + b); // Value of a: 10, value of B: 20
        // Exchange the values of two variables
       /* int temp = a;
        a = b;
        b = temp;
        System.out.println("a Value of: "+ A +", value of B: "+ b);*/

        // Exchanging the values of two variables is a frequent operation, so we can encapsulate it as a method
        ValueTransferTest test = new ValueTransferTest();
        // When the parameter is a basic data type, the "data value" of the argument basic data type variable is passed to the formal parameter, which is referred to as value transfer for short.
        test.swap(a, b);
        System.out.println("a Value of:" + a + ",b Value of:" + b); // Value of a: 10, value of B: 20
    }

    void swap(int a, int b) {
        int temp = a;
        a = b;
        b = temp;
    }
}

Reference passing

Overview:
When the parameter in the method is a reference data type, the method passes not the specific data, but the reference address, so there is no need to return data.
The parameter points to the address of the object that references the data type in heap memory. The parameter of the reference data type (address in heap memory) is compared to a key, and the object of the reference data type is compared to a house. As long as people with the same key share the room, they can operate the room.

Code example:

public class ArgsTransferTest3 {
    public static void main(String[] args) {
        int a = 10;
        int b = 20;

        /*int[] arr = new int[]{a,b};
        System.out.println("a Value of: "+ arr [0] +", value of B: "+ arr [1]); / / value of a: 10, value of B: 20
        ArgsTransferTest3 test = new ArgsTransferTest3();
        test.swap(arr);
        System.out.println("a Value of: "+ arr [0] +", value of B: "+ arr [1]); / / value of a: 20, value of B: 10*/

        DataSwap dataSwap = new DataSwap();
        dataSwap.a = a;
        dataSwap.b = b;
        System.out.println("a Value of:" + dataSwap.a + ",b Value of:" + dataSwap.b); // Value of a: 10, value of B: 20

        ArgsTransferTest3 test = new ArgsTransferTest3();
        test.swap(dataSwap);
        System.out.println("a Value of:" + dataSwap.a + ",b Value of:" + dataSwap.b); // Value of a: 20, value of B: 10
    }

    void swap(int[] arr) {
        int temp = arr[0];
        arr[0] = arr[1];
        arr[1] = temp;
    }

    void swap(DataSwap dataSwap) {
        int temp = dataSwap.a;
        dataSwap.a = dataSwap.b;
        dataSwap.b = temp;
    }
}

class DataSwap {
    int a;
    int b;
}

Example code for value passing and reference passing:

public class Compare {
    public static void main(String[] args) {

        int x = 1000;
        int values[] = {111, 222, 333, 444, 555};

        Compare com = new Compare();
        // void test(int num,int arr[])
        // Parameter transfer: transfer the value of x to num; Pass the value of values to arr
        // If x is the basic data type, the value transfer occurs, which is equivalent to copying 1000 to num, then modifying the value of num will not affect the original data;
        // Values is a reference data type. If reference transfer occurs, it is equivalent to pointing the arr to the address of values. Modifying the arr will affect the original data;
        com.test(x, values); // We modified the passed in value in test()

        // Modify the value passed in the method. Does it affect the original data?
        System.out.println("\n=========================");
        System.out.println("Original data x:" + x);
        System.out.print("Original data values:");
        for (int n : values) {
            System.out.print(n + "\t");
        }

    }

    // num is the basic data type; arr is a reference data type
    void test(int num, int arr[]) {
        System.out.println("num The value passed in is:" + num);
        System.out.print("arr The value passed in is:");
        for (int n : arr) {
            System.out.print(n + "\t");
        }
        // Reassign num
        num = 9999;

        // Reassign the arr subscript 2
        arr[2] = 666;

        System.out.println("\n After modification in the method num The value of is:" + num);
        System.out.print("After modification in the method arr The value of is:");
        for (int n : arr) {
            System.out.print(n + "\t");
        }
    }

}

Value passing and reference passing memory parsing

Parameter passing of basic data type

public static void main(String[] args) {
    int x = 5;
    System.out.println("Before modification x = " + x);// 5
    // x is an argument
    change(x);
    System.out.println("After modification x = " + x);// 5
}

public static void change(int x) {
    System.out.println("change:Before modification x = " + x);
    x = 3;
    System.out.println("change:After modification x = " + x);
}

Parameter passing of reference data type

public static void main(String[] args) {
    Person obj = new Person();
    obj.age = 5;
    System.out.println("Before modification age = " + obj.age);// 5
    // x is an argument
    change(obj);
    System.out.println("After modification age = " + obj.age);// 3
}

public static void change(Person obj) {
    System.out.println("change:Before modification age = " + obj.age);
    obj.age = 3;
    System.out.println("change:After modification age = " + obj.age);
}

// The Person class is defined as:
class Person{
    int age; 
}

 

public static void main(String[] args) {
    Person obj = new Person();
    obj.age = 5;
    System.out.println("Before modification age = " + obj.age);// 5
    // x is an argument
    change(obj);
    System.out.println("After modification age = " + obj.age);// 5
}
public static void change(Person obj) {
    obj = new Person();
    System.out.println("change:Before modification age = " + obj.age);
    obj.age = 3;
    System.out.println("change:After modification age = " + obj.age);
}
// The Person class is defined as:
class Person{
    int age; 
}

Method parameter transfer exercise:

1. The following program outputs the results and analyzes the memory storage model.

public class TransferTest1 {
    public void swap(int a, int b) {
        int tmp = a;
        a = b;
        b = tmp;
        System.out.println("swap In the method, a The value of is" + a + ";b The value of is" + b);
    }

    public static void main(String[] args) {
        TransferTest1 test = new TransferTest1();
        int a = 5;
        int b = 10;
        test.swap(a, b);
        System.out.println("After the exchange, the variable a The value of is" + a + ";variable b The value of is" + b);
    }
}

In the swap method, the value of a is 10; The value of b is 5
After the exchange, the value of variable a is 5; The value of variable b is 10

class DataSwap {
    public int a;
    public int b;
}

public class TransferTest2 {
    public static void swap(DataSwap ds) {
        int temp = ds.a;
        ds.a = ds.b;
        ds.b = temp;
        System.out.println("swap In the method, a Field The value of is" + ds.a + ";b Field The value of is" + ds.b);
    }

    public static void main(String[] args) {
        DataSwap ds = new DataSwap();
        ds.a = 5;
        ds.b = 10;
        swap(ds);
        System.out.println("After the exchange, a Field The value of is" + ds.a + ";b Field The value of is" + ds.b);
    }
}

In the swap method, the value of a Field is 10; The value of B field is 5
After the exchange, the value of a Field is 10; The value of B field is 5

public class TransferTest3 {
    public static void main(String args[]) {
        TransferTest3 test = new TransferTest3();
        test.first();
    }

    public void first() {
        int i = 5;
        Value v = new Value();
        v.i = 25;
        second(v, i);
        System.out.println(v.i);
    }

    public void second(Value v, int i) {
        i = 0;
        v.i = 20;
        Value val = new Value();
        v = val;
        System.out.println(v.i + " " + i);
    }
}

class Value {
    int i = 15;
}

15 0
20

Recursion method

Introduction

Master L. Peter Deutsch said: to iterate is human, to recurse, divide Man understands iteration, God understands recursion. There is no doubt that recursion is a wonderful way of thinking. For some simple recursive problems, we are always amazed at the ability of recursion to describe the problem and the simplicity of writing code, but it is not easy to truly understand the essence of recursion and flexibly use the idea of recursion to solve the problem. Before we formally introduce recursion, we give a vivid explanation of recursion and loops:

Recursion: you open the door in front of you and see another door in the house. You walk over and find that the key in your hand can still open it. You open the door and find that there is another door inside. You continue to open it. Several times later, when you open the door in front of you, you find that there is only one room and no door. Then, you start to return the same way. Every time you go back to a room, you count once. When you get to the entrance, you can answer how many doors you opened with this key.

Cycle: you open the door in front of you and see another door in the house. You walk over and find that the key in your hand can still open it. You push the door open, There is another door inside (if the front two doors are the same, then this door is the same as the front two doors; if the second door is smaller than the first door, then this door is also smaller than the second door. You continue to open this door until you open all the doors. However, the people at the entrance can't wait for you to go back and tell him the answer.

Connotation of recursion

Definition (what is recursion?)

In mathematics and computer science, recursion refers to the method of using function itself in the definition of function. In fact, recursion, as its name implies, contains two meanings: recursive and recursive, which is the essence of recursive thought.
    
Method recursion contains an implicit loop that repeats a piece of code, but this repetition does not need loop control.

Recursion must recurse in the known direction, otherwise this recursion will become infinite recursion, similar to an endless loop.

The connotation of recursion (what is the essence of recursion?)

As in the scenario described above, recursion is to go (pass) and return (return), as shown in the figure below. "Youqu" means that the recursive problem must be decomposed into several small-scale sub problems with the same form as the original problem. These sub problems can be solved with the same problem-solving ideas, just as the key in the above example can open the locks on all the back doors; "Youhui" means that the evolution process of these problems is a process from large to small, from near to far, and there will be a clear end point (critical point). Once this critical point is reached, there is no need to go to smaller and farther places. Finally, starting from this critical point, the original path returns to the origin and the original problem is solved.

More directly, the basic idea of recursion is to transform large-scale problems into small-scale similar subproblems. In particular, in function implementation, because the method to solve large problems and the method to solve small problems are often the same method, the function calls itself, which is the definition of recursion. It is particularly important that the function to solve the problem must have a clear end condition, otherwise it will lead to infinite recursion.

Understanding recursion by induction

We are not bad in mathematics. Our first reaction is what the mathematical model of recursion is. After all, we are much better at mathematical modeling than code modeling. By observing recursion, we will find that the mathematical model of recursion is actually mathematical induction, which is the most commonly used in high school series. Let's recall the mathematical induction.

Mathematical induction is suitable for transforming the original problem to its sub problem, and its sub problem becomes the sub problem of the sub problem. Moreover, we find that these problems are actually a model, that is, there are the same logical induction items. Of course, there is one exception, that is, the processing method at the end of induction is not applicable to our induction processing items, of course, it is not applicable, otherwise we will have infinite induction. In general, induction mainly includes the following three key elements:
Step expression: an expression that transforms a problem into a subproblem
End condition: when can I stop using step expressions
Direct solution expression: an expression that can directly calculate the return value under the end condition

In fact, this is why recursion can be used to solve some mathematical sequence problems by programming, such as the famous Fibonacci sequence problem.

Three elements of recursion

After we understand the basic idea of recursion and its mathematical model, how can we write a beautiful recursive program? It mainly focuses on the following three aspects:

1. Specify recursive termination conditions;
We know that recursion is going and returning. In this case, there must be a clear critical point. Once the program reaches this critical point, it doesn't need to continue to pass down, but starts to return. In other words, the critical point is a simple situation that prevents infinite recursion.

2. Give the handling method of recursive termination;
We just said that there is a simple situation at the critical point of recursion. In this simple situation, we should directly give the solution to the problem. Generally, in this situation, the solution of the problem is intuitive and easy.

3. Extract duplicate logic and reduce the scale of the problem.
When expounding the connotation of recursion, we said that the recursion problem must be decomposed into several sub problems with the same form as the original problem, which can be solved with the same problem-solving ideas. From the perspective of program implementation, we need to abstract a clean and repetitive logic in order to solve the subproblem in the same way.

Recursive application scenarios

In our actual learning work, recursive algorithms are generally used to solve three types of problems:
(1) the problem is defined recursively (fiboracci sequence, factorial,...);
(2) the solution of the problem is recursive (some problems can only be solved by recursive methods, such as Hanoi Tower problem,...);
(3) the data structure is recursive (linked list, tree and other operations, including tree traversal, tree depth,...).

Recursion and loop

Recursion and loop are two different typical ideas to solve problems.

Recursion usually directly describes the solution process of a problem, so it is also the easiest way to think of a solution. Loop actually has the same characteristics as recursion, that is, doing repetitive tasks, but sometimes the algorithm using loop does not clearly describe the problem-solving steps.

In terms of algorithm design alone, recursion and loop have no advantages or disadvantages. However, in practical development, because of the cost of function calls, recursion often brings performance problems, especially when the solution scale is uncertain; Because the loop has no function call overhead, it is more efficient than recursion. Recursive solution and loop solution are often interchangeable, that is, if you can easily use loop replacement where recursion is used without affecting the reading of the program, it is often good to replace with loop.

Converting a recursive implementation of a problem to a non recursive implementation generally requires two steps:
(1) create a "stack (some local variables)" to save these contents to replace the system stack, such as three non recursive traversal methods of the tree;
(2) turn the call to recursion into loop processing.

In the following, we will give some classic application cases of recursive algorithm. For the implementation of these cases, we will generally give recursive and non recursive solutions for everyone to experience.

Classic recursive problem practice

Factorial

public class Factorial {
    /**     
     * @description Recursive implementation of factorial
     */
    public static long f(int n){
        if(n == 1)   // Recursive termination condition 
            return 1;    // Simple scenario

        return n*f(n-1);  // Repeat the same logic to reduce the scale of the problem
    }

    /**     
     * @description Non recursive implementation of factorial
     */
    public static long f_loop(int n) {
        long result = n;
        while (n > 1) {
            result = result * n;
            n--;
        }
        return result;
    }
}

Fibonacci sequence

Fibonacci sequence, also known as golden section sequence, refers to such a sequence: 1, 1, 2, 3, 5, 8, 13, 21; Mathematically, Fibonacci sequence is defined recursively as follows: F0=0, F1=1, Fn=F(n-1)+F(n-2) (n > 2).

public class FibonacciSequence {

    /**
     * @description Classical recursive method
     * Fibonacci numbers are as follows:
     * 1,1,2,3,5,8,13,21,34,...
     * Then, when calculating fib(5), you need to calculate FIB (4), FIB (3) and fib(2) once, and call fib(1) * twice, that is:
     * fib(5) = fib(4) + fib(3)
     * fib(4) = fib(3) + fib(2) ;fib(3) = fib(2) + fib(1)
     * fib(3) = fib(2) + fib(1)
     * This involves a lot of repeated calculations. In fact, we only need to calculate fib(4), fib(3), fib(2) and fib(1) once,
     * The later optimizeFibonacci function is optimized to reduce the time complexity to O(n)
     */
    public static int fibonacci(int n) {
        if (n == 1 || n == 2) {     // Recursive termination condition
            return 1;       // Simple scenario
        }
        return fibonacci(n - 1) + fibonacci(n - 2); // Repeat the same logic to reduce the scale of the problem
    }

    /**
     * @description Non recursive solution: there is no return
     */
    public static int fibonacci_loop(int n) {

        if (n == 1 || n == 2) {
            return 1;
        }

        int result = -1;
        int first = 1;      // Maintain your own "stack" for status backtracking
        int second = 1;     // Maintain your own "stack" for status backtracking

        for (int i = 3; i <= n; i++) { // loop
            result = first + second;
            first = second;
            second = result;
        }
        return result;
    }


}

3, Class member 3: constructor

Constructor syntax format

As mentioned above, the following syntax is used to create objects
Class name object name = new class name ();  
The essence is to call the constructor:
The keyword new, commonly referred to as the create operator, is used to allocate object memory and initialize the memory to the default value.
Once new has allocated and initialized memory, it will call the constructor to perform object initialization.
Note: when you create a class, you just create a new data type. An object is an instance of a class. Creating a class is not creating an object.

    Constructor is a special method (ambiguous) of object, which mainly displays:
        The method name of the constructor is the same as the class name.
        Constructor has no return type. (and declared as void (different)
        Constructor can not be written, and the system will assign a parameterless constructor by default;
        Main functions of constructor:
			1,Create an object.
			2,Complete the initialization of the object.
		Constructor cannot be static,final,synchronized,abstract,native Decoration, no return Statement return value

	Syntax format:
		Modifier class name (parameter list) {
        	Initialization statement;
        } 

	According to different parameters, constructors can be divided into the following two categories:
		Implicit parameterless constructor (provided by default)
		Explicitly define one or more constructors (no parameters, with parameters)

Example code:

When we are born, some people have names after birth, but some people have names once they are born. So how do we assign values to objects once they are created in java?

public class Person {

    String name; // full name
    int age; // Age

    public static void main(String[] args) {
        // The p object of Person type is created, and the Person() here is actually a constructor; And it is provided by default;
        Person p = new Person();

        System.out.println("full name: " + p.name + " Age: " + p.age); // name = null, age = 0;
        // The child had no name and age at birth
    }
}    
public class Person {

    String name; // full name
    int age; // Age

    // Construction method
    Person(String pname, int page) {
        name = pname; // Give the object a name value
        age = page; // Give the object an age value
    }

    public static void main(String[] args) {
        // The p object of Person type is created, and the constructor is called to assign the attribute value to the object
        Person p = new Person("Zhang San", 1);
        System.out.println("full name: " + p.name + " Age: " + p.age); // name = Zhang San, age = 1;
        // The child had a name and age when he was born
    }
}

explain:

In the Java language, each class has at least one constructor.
The modifier of the default constructor is consistent with that of its class.
Once a constructor is explicitly defined, the system no longer provides a default constructor.
A class can create multiple overloaded constructors.
The constructor of a parent class cannot be inherited by a child class.

public class Person {

    String name; // full name
    int age; // Age

    // Full parameter construction method
    Person(String pname, int page) {
        name = pname; // Give the object a name value
        age = page; // Give the object an age value
    }

    // Nonparametric construction method
    Person() {

    }

    public static void main(String[] args) {
        Person p = new Person("Zhang San", 1); 
        /*
          According to the number of arguments to create the object, the jvm goes back to find the appropriate construction method,
          All two arguments call a constructor with two parameters Person(String name,int age)
         */
        System.out.println("full name: " + p.name + " Age: " + p.age); // name = Zhang San, age = 1;
    }
}

Differences between constructors and ordinary functions:

(1) ordinary functions are used to define the functions that an object should have. The constructor defines what the object should have when it is created before calling the function. That is, the initialization content of the object.

(2) the constructor is called by the jvm when the object is created to initialize the object. A normal function is executed only when the object calls the function after the object is established.

(3) ordinary functions can be called multiple times with an object, and the constructor is called when the object is created.

(4) the function name of the constructor should be the same as the class name, while ordinary functions can only comply with the naming rules of identifiers.

(5) the constructor has no return value type.

Constructor Overload

Constructors are generally used to initialize objects while creating them. For example:
        class Person{
            String name;
            int age;
            public Person(String n , int a){ name=n; age=a;}
        }

Constructor overloading makes the creation of objects more flexible and convenient to create various objects.
Constructor overload, parameter list must be different

Example code:

public class Person {
    private String name;
    private int age;
    private Date birthDate;

    public Person(String n, int a, Date d) {
        name = n;
        age = a;
        birthDate = d;
    }

    public Person(String n, int a) {
        name = n;
        age = a;
    }

    public Person(String n, Date d) {
        name = n;
        birthDate = d;
    }

    public Person(String n) {
        name = n;
        age = 30;
    }
}

Summary: attribute assignment process

So far, we have talked about a lot of places where you can assign values to the properties of a class. These positions are summarized and the order of assignment is indicated.

Location of assignment:
① default initialization
② explicit initialization
③ initialization in constructor
④ assign values through "object. Attribute" or "object. Method"
    
Order of assignment:
                ① - ② - ③ - ④

public class UserTest {
    public static void main(String[] args) {
        User u = new User();

        System.out.println(u.age);

        User u1 = new User(2);

        System.out.println(u1.age);

        u1.setAge(3);
        u1.setAge(5);

        System.out.println(u1.age);
    }
}

class User {
    String name;
    int age = 1;

    public User() {

    }

    public User(int a) {
        age = a;
    }

    public void setAge(int a) {
        age = a;
    }
}

4, Keyword: this

What is this?
In Java, this keyword is difficult to understand, and its function is very close to its meaning.
It is used inside the method, that is, the reference of the object to which the method belongs;
It is used inside the constructor to represent the object that the constructor is initializing.
    
this can call the properties, methods, and constructors of a class.
When to use this keyword?
this is used when the object calling the method needs to be used in the method.
Specifically: we can use this to distinguish between attributes and local variables.
For example: this name = name;

Use this to call properties and methods

1. In any method or constructor, if you use the member variable or member method of the current class, you can add this in front of it to enhance the readability of the program. However, usually we are used to omitting this.
2. When the shape participating member variable has the same name, if you need to use the member variable in the method or constructor, you must add this to indicate that the variable is a member variable of the class.
3. When using this to access properties and methods, if it is not found in this class, it will be found from the parent class.

class Person { // Define the Person class
    private String name;
    private int age;

    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public void getInfo() {
        System.out.println("full name:" + name);
        this.speak();
    }

    public void speak() {
        System.out.println("Age:" + this.age);
    }
}
class Person { // Define the Person class
    String name;

    Person(String name) {
        this.name = name;
    }

    public void getInfo() {
        System.out.println("Person class --> " + this.name);
    }

    public boolean compare(Person p) {
        return this.name == p.name;
    }
}

// The object currently operating this method is called the current object.
public class PersonTest {
    public static void main(String args[]) {
        Person per1 = new Person("Zhang San");
        Person per2 = new Person("Li Si");
        per1.getInfo(); // The object that currently calls the getInfo() method is per1.
        per2.getInfo(); // The object that currently calls the getInfo() method is per2.
        boolean b = per1.compare(per2);
    }
}

Use this to call the constructor of this class

        4.this can be used as a special format for constructors in a class to call each other.

class Person { // Define the Person class
    private String name;
    private int age;

    public Person() { // Parameterless constructor
        System.out.println("New object instantiation");
    }

    public Person(String name) {
        this(); // Call the parameterless constructor in this class
        this.name = name;
    }

    public Person(String name, int age) {
        this(name); // Call constructor with one parameter
        this.age = age;
    }

    public String getInfo() {
        return "full name:" + name + ",Age:" + age;
    }
}

reflection:
When we initialize an object, what should we do if we want to execute some duplicate code?
1, define the duplicate code in a member method, calling the member method;
2, define the duplicate code in a construction method and call the construction method.

be careful:
You can use the "this (formal parameter list)" method in the constructor of the class to call other constructors overloaded in this class!
Clear: the constructor cannot call its own constructor by means of "this (formal parameter list)".
If n constructors are declared in a class, "this" is used in up to n - 1 constructors.
"This (formal parameter list)" must be declared on the first line of the constructor of the class!
At most one "this (formal parameter list)" can be declared in a constructor of a class.

JDK example:
HashMap, String, etc

5, Keywords: package, import

Keyword - package

	Cause: when we design a program (especially multi person cooperation), we will write some classes to implement functions, but there are often duplicate names. In order to solve this problem, we specially designed a package. (there are other functions)

	Simple understanding: there are communities with the same name between different cities. These communities with the same name can be distinguished by the city name. The city name can be understood as the package above, and the community can be regarded as a class with the same name. Through this prefix, the problem of duplicate name is solved.

	To better organize classes, Java A package mechanism is provided to distinguish the namespace of class names. In fact, it can be understood as a folder, and the storage method of tree directory is used.

	package Statement as Java The first statement in the source file indicates the package of the class defined in the file.(If this statement is defaulted, it is specified as an anonymous package). 

	Its format is:
		package Top level package name.Sub package name ;

	give an example:
		File system structure: pack1\pack2\PackageTest.java
		package pack1.pack2; //The specified class PackageTest belongs to package Pack1 pack2
        public class PackageTest{
            public void display(){
            	System.out.println("in method display()");
            }
        }

	The package corresponds to the directory of the file system, package In the statement, use“." To indicate the package(catalogue)Hierarchy of;
	Packets are usually identified by lowercase words. Usually use the inversion of your company's domain name:

Function of package:

Packages help manage large software systems: classify classes with similar functions into the same package. For example: MVC design pattern.
Packages can contain classes and sub packages, which are divided into project levels for easy management.
Resolve class naming conflicts.
Control access rights.

Introduction to main packages in JDK

        1. java.lang ---- contains some core classes of Java language, such as String, Math, Integer, System and Thread, and provides common functions
        2. java.net ---- contains classes and interfaces that perform network related operations.
        3. java.io - contains classes that can provide multiple input / output functions.
        4. java.util - contains some utility classes, such as defining system features, collection framework classes of interfaces, and using functions related to date and calendar.
        5. java.text ---- contains some Java formatting related classes
        6. java.sql ---- contains the relevant classes / interfaces for JDBC database programming with Java
        7. java.awt --- contains several classes that make up the abstract window toolkits, which are used to build and manage the graphical user interface (GUI) of the application.

Keyword - import

	To use the defined in different packages Java Class, required import Statement to introduce classes or all classes required under the specified package hierarchy(.*). import Statement tells the compiler where to look for classes.
	Syntax format: import Package name.Class name;

	Application examples:
		import pack1.pack2.Test; //import pack1.pack2.*; Indicates the introduction of Pack1 All structures in the pack2 package
        public class PackTest{
            public static void main(String args[]){
                Test t = new Test(); //The Test class is in Pack1 Defined in pack2 package
                t.display();
            }
        }

	be careful:
        1. Use in source files import Explicitly import the classes or interfaces under the specified package.
        2. The declaration is between the declaration of the package and the declaration of the class.
        3. If you need to import more than one class or interface, you can explicitly import more than one in parallel import Statement.
        4. Example: you can use java.util.*One time import util All classes or interfaces under the package.
        5. If the imported class or interface is java.lang If it is under the package or under the current package, this can be omitted import sentence.
        6. If you use classes with the same name under different packages in your code. Then you need to use the full class name of the class to indicate which class is called.
        7. If already imported java.a Class under package. So if you need to use a The classes under the sub package of the package still need to be imported.
        8. import static Use of combination: call static properties or methods under the specified class or interface
import static java.lang.System.*;
import static java.lang.Math.*;

public class PackageImportTest {
    public static void main(String[] args) {

        out.println("hello");

        long num = round(123.434);
    }
}

Keywords: Java Back-end

Added by davidx714 on Tue, 25 Jan 2022 06:11:28 +0200