Introduction to JAVA -- the fourth lesson

Posted by darcuss on Sat, 05 Feb 2022 09:51:01 +0100

method

Statement block

Statement block (also called compound statement).
The variables defined in the statement block can only be used for themselves and cannot be used externally.

//(that is, a statement block can use external variables, while external variables cannot)
public class Test19 {
    public static void main(String[ ] args) {
        int n;
        int a;
        {
            int k;
            int n;//Compilation error: variable n cannot be defined repeatedly
        } //This ends the scope of variable k
    }
}

method

Method: a piece of code used to complete a specific function, similar to the function of other languages.

Method is used to define the behavior characteristics and function implementation of the class or instances of the class.
In process oriented, function is the most basic unit, and the whole program is composed of function calls.

In object-oriented, the basic unit of the whole program is class, and the method is subordinate to class and object.

Method overload

Overloading: multiple methods with the same name but different formal parameter lists can be defined in a class. (the overloaded method is actually a completely different method, only with the same name)

Conditions that constitute method overloading:

  1. Different meanings of formal parameter list: different types, numbers and order of formal parameters
  2. Only different return values do not constitute method overloading. For example, int a(String str) {} and void a(String str) {} do not constitute method overloading
  3. Only the names of formal parameters are different, which does not constitute method overloading. For example, int a(String str) {} and int a(String s) {} do not constitute method overloading

[example] method overload

public class Test21 {
    public static void main(String[ ] args) {
        System.out.println(add(3, 5));// 8
        System.out.println(add(3, 5, 10));// 18
        System.out.println(add(3.0, 5));// 8.0
        System.out.println(add(3, 5.0));// 8.0
// We have seen the overloading of methods
        System.out.println();// 0 parameters
        System.out.println(1);// The argument is an int
        System.out.println(3.0);// The parameter is a double
    }
    /** Summation method */
    public static int add(int n1, int n2) {
        int sum = n1 + n2;
        return sum;
    }
    // The same method name and different number of parameters constitute an overload
    public static int add(int n1, int n2, int n3) {
        int sum = n1 + n2 + n3;
        return sum;
    }
    // The same method name and different parameter types constitute an overload
    public static double add(double n1, int n2) {
        double sum = n1 + n2;
        return sum;
    }
// The same method name and different parameter order constitute an overload
public static double add(int n1, double n2) {
    double sum = n1 + n2;
    return sum;
}
    //Compilation error: only the return value is different, which does not constitute an overload of the method
    public static double add(int n1, int n2) {
        double sum = n1 + n2;
        return sum;
    }
    //Compilation error: only the parameter names are different, which does not constitute an overload of the method
    public static int add(int n2, int n1) {
        double sum = n1 + n2;
        return sum;
    }
}

practice:
Define a method to deal with the company's lateness problem:
(1) Input: late time, monthly salary.
(2) Processing logic:
1. 1-10 minutes late, warning.
2. If you are 11-20 minutes late, you will be fined 100 yuan.
3. If you are late for 21-30 minutes, you will be fined 200 yuan.
4. If you are late for more than 30 minutes, half day salary will be deducted.
5. If you are late for more than 1 hour, it shall be calculated as absenteeism, and the salary of 3 days shall be deducted.
(3) Output: penalty amount

public class TestMethod2 {
    /**
     * (1)Input parameters: late time, monthly salary.
     * (2)Processing logic:
     * ①1-10 minutes late, warning.
     * ②If you are 11-20 minutes late, you will be fined 100 yuan.
     * ③If you are late for 21-30 minutes, you will be fined 200 yuan.
     * ④Half day salary will be deducted if you are late for more than 30 minutes.
     * ⑤If you are late for more than 1 hour, it will be calculated as absenteeism, and the salary of 3 days will be deducted.
     * (3)Output penalty amount
     */
    public static int late(int lateMinute,double salary){
        int fakuan = 0;       //fine
        if(lateMinute<11){
            System.out.println("Warning! Can't be late!!");
        }else if(lateMinute<21){
            fakuan = 100;
        }else if(lateMinute<31){
            fakuan = 200;
        }else if(lateMinute<61){
            fakuan = (int)(salary/(21.75*2));     //21.75 refers to: average working days per month
        }else{
            fakuan = (int)(salary*3/(21.75));
        }

        System.out.println("Late time:"+lateMinute+",Penalty: "+fakuan);
        return fakuan;
    }
    public static void main(String[] args) {
        late(45,42000);
    }
}

Recursive structure

The basic idea of recursion is "call yourself". It is useful in many algorithms such as DFS (depth first search).

The recursive structure consists of two parts:
The port defines a recursive header. Solution: when not to call its own method. If there is no head, it will fall into an endless loop, that is, the end condition of recursion.
Mouth recursion. Solution: when you need to call your own method.

[example] use recursion to find n!

public class Test22 {
    public static void main(String[ ] args) {
        long d1 = System.curentTimeMilis();
        factorial(10);
        long d2 = System.curentTimeMilis();
        System.out.printf("Recursive time-consuming:" +(d2-d1));   //Time: 32ms
    }
    /** Factorial method*/
    static long   factorial(int n){
        if(n==1){//Recursive header
            return 1;
        }else{//Recursive body
            return n*factorial(n-1);//n! = n * (n-1)!
        }
    }
}

[example] use the loop to find n!

public class Test23 {
    public static void main(String[ ] args) {
        long d3 = System.curentTimeMilis();
        int a = 10;
        int result = 1;
        while (a > 1) {
            result *= a * (a - 1);
            a -= 2;
        }
        long d4 = System.curentTimeMilis();
        System.out.println(result);
        System.out.printf("Ordinary cycle time:  " + (d4 - d3));
    }
}

Recursive defect
The simplicity of the algorithm is one of the advantages of recursion.
However, recursive calls will occupy a lot of system stack and consume a lot of memory. When there are many levels of recursive calls, the speed is much slower than the loop, so we should be careful when using recursion.
The running results of recursion and loop in the above example are compared

Object oriented programming

Table structure and class structure


The structure of Employee class and employee table is exactly the same. However, the Employee class adds data types.

-Table actions and class methods

-Object corresponds to "row data in table"

In object-oriented programming, remember the following three sentences:

  1. Table structure correspondence: class structure
  2. One row of data corresponds to one object
  3. All data in the table correspond to: all objects of this class
//The following four lines of data need to be represented in this way when we use four objects (assuming that there is a corresponding construction method, the following code is schematic, not real code):
emp1 = new Employee(ID:1001, name:"Xiao Yi Gao", job:"programmer", baseSalary:20000, salary2:0, hiredate:"9 January 1", address:"Beijing"); 
emp2 = new Employee(ID:1002, name:"Gao Xiaoer", job:"Reception", baseSalary:5000, salary2:0, hiredate:"9 February 2", address:"Beijing"); 
emp3 = new Employee(ID:1003, name:"Gao Xiaosan", job:"salesperson", baseSalary:3000, salary2:15000, hiredate:"9 January 1", address:"Zhengzhou");
emp4 = new Employee(ID:1004, name:"Gao Xiaosi", job:"Finance", baseSalary:5000, salary2:0, hiredate:"9 February 2", address:"Shanghai");

Process oriented and object-oriented ideas

Process oriented is suitable for simple transactions that do not require collaboration, focusing on how to execute.
Object oriented can help us grasp and analyze the whole system from a macro perspective. [the idea of oriented object is more in line with people's thinking mode. The first thing we think about is "how to design this thing?" However, the specific micro operations (i.e. methods) of the implementation part still need to be handled with process oriented thinking.]

-The difference between process oriented and object-oriented

·Summary of object-oriented and process oriented ideas
 they are all ways of thinking to solve problems and the way of code organization.
 process oriented is a kind of "executor thinking", which can be used to solve simple problems.
 object oriented is a kind of "designer thinking", which can be used to solve complex problems requiring cooperation.
 object oriented is inseparable from process oriented:
 macroscopically: overall design through object-oriented
 at the micro level: executing and processing data is still process oriented.

Object oriented is "designer thinking"

Object oriented is a kind of "designer thinking".
When designing, first find nouns from the problem, then determine which of these nouns can be used as classes, and then determine the relationship between classes according to the attributes and methods of the classes determined by the needs of the problem.

-Object oriented analysis: writing poetry


First, find out nouns from the scene and use tables to express them.

After analyzing the above objects, we need to combine them. Integrate these objects into one scene.

-Object oriented analysis: writing novels

Writing a novel is essentially the same as designing software. According to the content you want to express, you can design different scenes and tasks.
After the design is completed, the author writes chapter by chapter (execution stage).

Taking the short story teahouse as an example, this paper briefly analyzes the process of "writing novels in object-oriented design"

  1. Clarify the main content and objectives of the novel

  2. Character design analysis

  3. Overall event design

-The evolutionary history of objects (what data management and enterprise management have in common)

summary
 to put it bluntly, object is also a data structure (management mode of data), which puts data and data behavior together.
 in memory, an object is a memory block that stores relevant data sets!
 the essence of an object is a way of organizing data!

-Detailed explanation of objects and classes

Class: class.
Object: object, instance. (later, we will say that the object of a class and the instance of a class have the same meaning)

 a class can be regarded as a template of a class of objects, and objects can be regarded as a concrete instance of the class.
 class is an abstract concept used to describe objects of the same type. The class defines the common attributes and methods of this kind of objects.

Class definition

[example] how to define a class

// Each source file must have and only have one public class, and the class name and file name must be consistent!
public class Car { 
}
class Tyre { // A Java file can define multiple class es at the same time 
}
class Engine {
}
class Seat { 
}

For a class, there are three kinds of members: attribute field, method and constructor.

-Attribute (field member variable)

Property is used to define the data or static characteristics contained in this class or this class of objects. Attribute scope is the whole class body. When defining a member variable, you can initialize it. If it is not initialized, Java initializes it with the default value.

Attribute definition format:

[Modifier ] Property type property name = [Default value] ;

-Method

Method is used to define the behavior characteristics and function implementation of the class or instances of the class. Methods are abstractions of the behavioral characteristics of classes and objects. In object-oriented, the basic unit of the whole program is class, and the method is subordinate to class and object.

[Modifier ] Method return value type method name(parameter list ) { 
// n statements
}

[example] write a simple student class

public class SxtStu { 
	//Properties (member variables)
 	int id;
 	String sname; 
 	int age; 
 	//method
  	void study(){ 
  		System.out.println("I am learning!"); 
  }
	//Construction method 
	SxtStu(){ 
	} 
}

Simple memory analysis (help understand object-oriented)

-Construction method (constructor)

Constructors are used to initialize objects, not create objects [the construction method is responsible for initialization (decoration), not building houses]

Declaration format:

[Modifier ] Class name(parameter list ){
	//n statements 
} 

Constructor 4 key points:

 the constructor calls through the new keyword!!
 although the constructor has a return value, it cannot define the type of return value (the type of return value must be this class), and it cannot use return to return a value in the constructor.
 if we do not define a constructor, the compiler will automatically define a parameterless constructor. If defined, the compiler will not add it automatically!
 the method name of the constructor must be consistent with the class name!

practice:
Define a "Point" class to represent a Point in two-dimensional space (with two coordinates). The requirements are as follows:
 point objects with specific coordinates can be generated.
• provide a method to calculate the distance between this "point" and another point

class Point { 
    double x, y;
    public Point(double _x, double _y) { 
        x = _x; 
        y = _y; 
    }
    public double getDistance(Point p) { 
        return Math.sqrt((x - p.x) * (x - p.x) + (y - p.y) * (y - p.y)); 
    }
    public static void main(String[ ] args) { 
        Point p1 = new Point(3.0, 4.0);
        Point origin = new Point(0.0, 0.0); 
        System.out.println(p1.getDistance(origin)); 
    } 
}

Overloading of construction methods

The construction method is also a method. Like ordinary methods, constructors can also be overloaded
[example] construction method overloading (creating different user objects)

public class User {
    int id; // id
    String name; // Account name
    String pwd; // password
    public User() {

    }
    public User(int id, String name) {//If the formal parameter name and attribute name are the same in the method construction, you need to use this keyword to distinguish between attributes and formal parameters. this.id indicates the attribute id; id represents parameter id
        this.id = id;
        this.name = name;
    }
    public User(int id, String name, String pwd) {
        this.id = id;
        this.name = name;
        this.pwd = pwd;
    }
    public static void main(String[ ] args) {
        User u1 = new User();
        User u2 = new User(101, "Big whine");
        User u3 = new User(100, "Small whine", "123456");
    }
}

Topics: Java Back-end