Mad Theology Java Zero-Basic Study Notes

Special thanks to Kuangshen for his company on the Java full-stack road.
Video address: https://www.bilibili.com/video/BV12J41137hu?p=1

Java installation

HelloWorld

After installing the JDK 11 version (Baidu will start using JDK 11 around 2020, instead of JDK 8 as before)

Write the following code in Notepad++, and save it as helloworld.java, and then it is full of ceremonial helloworld

public class helloworld{
    
    
	public static void main(String[] args){
    
    
		System.out.print("Hello,World!");
	}
}

After saving, start the cmd command line in the folder directory (just type cmd directly before the file path, or cd to the file location in the command line)

Please add a picture description

Java runtime mechanism

Compile and Interpret Mixed Languages

insert image description here

IDEA installation

insert image description here

insert image description here

IDEA shortcut keys

insert image description here

After creating a new project, we complete the code of Hello World again. This time we use shortcut keys, which are the first letters of each keyword. psvm and sout represent the whole block of code below

public static void main(String[] args){
    
    } // psvm
System.out.print("Hello,World!");  // sout

Java Basic Syntax

1. Notes

Comments are not only for others to read, they are actually a note of the code, which is convenient for yourself and others to read

public class HelloWorld {
    
    
    public static void main(String[] args) {
    
    
        // 单行注释
        // 输出一个HelloWorld
        System.out.println("HelloWorld");
        /*
        多行注释
         */
        // JavaDoc:文档注释  /**  */
        /**
         * @description HelloWorld
         * @author Marine
         */
    }
}

Among them, each @ in the document comment has its specific meaning. Generally, when large companies standardize their work, they need to write at the beginning

2. Identifier

That is, reserved words, which need to be distinguished when naming, and identifiers are case-sensitive

All identifiers should begin with a letter (AZ or az), a dollar sign ( ), or an underscore ( ). The initial can be followed by a letter ( A − Z or a − z ), a dollar sign ( ), or an underscore ( ). The first letter can be followed by a letter (AZ or az), a dollar sign () , or start with an underscore ( ) . After the initial letter can be a letter ( AZ or az ) , dollar sign ( ), underscore () or any combination of numbers, but keywords cannot be used as variable names or method names.

3. Data type

Java is a strongly typed language : the use of variables is required to strictly comply with the regulations, so variables must be defined before they can be used (strong type has the advantage of high security, relatively speaking, it is slower)

public class Demo02{
    
    
    public static void main(String[] args){
    
    
        String a = "hello";
        int num = 10;
        System.out.println(a);
        System.out.println(num);
    }
}

Eight data types

public class Demo03{
    
    
	public static void main(String[] args){
    
    
	// 八大基本数据类型
	
	// 整数
	int num1 = 10;
	byte num2 = 20;
	short num3 = 30;
	long num4 =40L;
	
	// 小数:浮点数
	float num5 = 50.1F; // float类型要在数字后面加个F
	double num6 = 3.141592653;

	// 字符类型
	char name = 'a'; // 字符指的是一个字母
	// 字符串,String 不是关键字,是一个类
	String namea = "秦疆";
	
	// 布尔型:是非
	boolean flag = true;
	// boolean flag = false;
	}
}

4. Data type expansion

public class Demo04{
    
    
	public static void main(String[] args){
    
    
	// 整数拓展 进制 二进制以0b开头 八进制以0开头 十进制 十六进制以0x开头
	int num1 = 10; // 十进制10
	int num2 = 010; // 八进制的10 也就是十进制的8
	int num3 = 0x10; // 十六进制的10 也就是十进制的16
	System.out.println(num1); // 10
	System.out.println(num2); // 8
	System.out.println(num3); // 16

	// ======================================================
	// 浮点数拓展
	// 金融公司用 float 和 double 计算钱会有问题
	float f = 0.1f; // 0.1
	double d = 1.0 / 10; // 0.1
	System.out.println(f==d); // false

	// float 表现的字长是有限、离散的 存在舍入误差,只能提供接近但不等于的值
	// 最好避免使用浮点数进行比较
	float f1 = 1212121212121212f;
	float f2 = f1 + 1;
	System.out.println(f1==f2); // false

	// 有一个 BigDecimal 数字工具类进行表示
	// ======================================================
	// 字符拓展 所有的字符本质都是数字 编码问题 Unicode 对字母汉字进行编码
	char c1 = ‘a’;
	char c2 = '中';
	System.out.println(c1);
	System.out.println(int(c1)); // 强制转换数据类型到int
	System.out.println(c1);
	System.out.println(int(c1));

	// 转义字符 \t 制表符  \n 换行
	System.out.println(Hello\tWorld!\t”);
	}
}

Type conversion
Since Java is a strongly typed language, type conversion is required when performing some operations

低  ---------------------------------------->  高
byte,short,char -> int -> long -> float -> double

In the operation, different types of data are first converted into the same type, and then the operation is performed (because the capacity is different, the range is different)

public class Demo04{
    
    
   public static void main(String[] args){
    
    
   int i = 128;
   byte b = (byte)i; // 内存溢出 b=-128 因为byte 范围 -128~127
   // 强制转换  高-->低 (类型)变量名  
   // 自动转换  低-->高
   /*
   注意点:
   1.不能对布尔值进行转换
   2.不能把对象类型转换为不相干的类型
   3.把高容量转换到低容量的时候,强制转换
   4.转换的时候可能存在内存溢出,或者精度问题
   */
   System.out.println(===================);
   System.out.println((int)23.7); // 23  将double的23.7转换为int 
   System.out.println((int)-45.89f); // -45  将float的-45.89转换为int

5. Variables

Java variable is a strongly typed language, each variable must declare its type, Java variable is the most basic storage unit in the program, its elements include variable name, variable type and scope, its essence is a memory address name

	type varName [=value] [{
    
    , varName[=value]}];
//数据类型 变量名   =	值; 
//可以用逗号隔开来声明多个类型变量,但是不推荐这样做保证程序可读性

Note that a variable declaration is a complete statement, so it must end with a semicolon;

6. Constants

Constants cannot be changed after initialization! A value that does not change.

A constant can be understood as a special variable whose value is not allowed to be changed during the running of the program after its value is set

final 常量名=值;
final double PI=3.14//常量名一般使用大写字母表示
 
public class Demo09{
    
    
    //修饰符不区分前后位置,其中static和final都是修饰符,使用两种输出结果相同
    static final double PI = 3.14;
    // final static double PI = 3.14;
    public static void main(String[] args){
    
    
        System.out.println(PI);
    }
}

variable naming convention

  • All variables, methods, and class names: see the name and know the meaning
  • Class member variables, local variables, and method names: the first letter is lowercase and camel case (except for the first word, the first letter of the following word is capitalized lastName)
  • Class names: initial capitalization and camelCase principles
  • Constants: capital letters and underscores MAX_NUM

7. Operators

  • Arithmetic operators: + - * / % ++ –
  • Assignment operator: =
  • Relational operators: >, <, >=, <=, ==, !=, instanceof
  • Logical operators: && , ||, !
  • Bitwise operators: &, |, ^, ~, >>, <<, >>>
  • Conditional operator: ?:
  • Extended assignment operators: +=, -=, *=, /=
package baseDemo;

public class demo02 {
    
    
    public static void main(String[] args) {
    
    
        // 一元运算符:自增 ++ 自减 --
        int a = 3;
        int b = a++; // a++ 是先赋值后自增,所以此时b=3,语句结束后a=4
        System.out.println(a); // 4
        int c = ++a; // 推荐使用++a 是先自增后赋值,所以赋值前a=5, c=5

        System.out.println(a); // 5
        System.out.println(b); // 3
        System.out.println(c); // 5

        // 幂运算,等需要使用 Math 工具类进行运算
        double power = Math.pow(2, 3);
        System.out.println(pow);
    }
}
package baseDemo;

public class demo03 {
    
    
    public static void main(String[] args) {
    
    
        // 逻辑运算:与或非
        boolean a = true;
        boolean b = false;

        System.out.println("a && b: " + (a && b)); // 两个都为真才为真
        System.out.println("a || b: " + (a || b)); // 两个为假才为假
        System.out.println("!(a && b): " + (!(a && b)));
    }
}

/*
a && b: false
a || b: true
!(a && b): true
Process finished with exit code 0
*/

Package Mechanism - Similar to Folders

In order to better organize classes, Java provides a package mechanism to distinguish the namespace of the class name. The
syntax format of the package statement is:

package com.kuangstudy.www // 用 . 隔开各个层级文件夹

Generally, the company domain name is inverted as the package name; sometimes in order to use a member of a certain package, we need to explicitly import the package in the Java program. Just use the import statement.

import com.kuangstudy.* //  .* 是通配符表示该层级下所有文件

JavaDoc

The javadoc command is used to generate your own API documentation

  • @author author name
  • @version version number
  • @since indicates the earliest JDK version required
  • @param parameter name
  • @return return value case
  • @throws exception throwing condition

Java flow control

1. Scanner object

java.util.Scanner is a new feature of Java5, we can obtain user input through the Scanner class.

Scanner s = new Scanner(System.in);

The input string is obtained through the next() and netxLine() methods of the Scanner class. Before reading, we generally need to use hasNext() and hasNextLine() to determine whether there is any input data.

package scanner;

import java.util.Scanner;

public class Demo01 {
    
    
    public static void main(String[] args) {
    
    
        // 创建一个扫描对象,用于接受键盘数据
        Scanner scanner = new Scanner(System.in);
        System.out.println("使用next方式接受:");

        // 判断用户有没有输入字符串
        if (scanner.hasNext()){
    
    
            // 使用next方式接受
            String str = scanner.next();
            System.out.println("输出的内容为:" + str );
        }

        // 关闭 Scanner ,解除 IO 流资源占用
        scanner.close();
    }
}

// 输出界面如下
使用next方式接受:
hello world		
输出的内容为:hello		
// 由于使用的是 scanner.next() 一次读入一个单词以空格划分,若使用 scanner.nextLine() 则是 hello world

Process finished with exit code 0

next() method:

  1. Be sure to read valid characters before you can end the input
  2. For blanks encountered before entering valid characters, the next() method will automatically remove them
  3. Only after valid characters are entered, the blank space after it is used as a separator or end character
  4. next() cannot get a string with spaces

nextLine():

  1. End with Enter, that is to say, the nextLine() method returns all the characters before entering the carriage return
  2. can get blank
package scanner;

import java.util.Scanner;

public class Demo01 {
    
    
    public static void main(String[] args) {
    
    
        // 创建一个扫描对象,用于接受键盘数据
        Scanner scanner = new Scanner(System.in);
        // 计算数值的和
        double sum = 0;
        // 计算有多少个数
        int count = 0;
        System.out.println("使用next方式接受:");

        // 通过循环判断是否还有输入,并在里面对每一次进行求和统计
        while(scanner.hasNextDouble()){
    
    
            double num = scanner.nextDouble(); // 读取数字赋值给中间变量 num
            count++; // 将计数器加1
            sum += num;
        }

        System.out.println(count + "个数的和为" + sum);
        System.out.println(count + "个数的平均值是" + (sum / count));

        // 关闭 Scanner ,解除 IO 流资源占用
        scanner.close();
    }
}

// 输出界面如下
使用next方式接受:
10
20
30
40
x		// 输入不是 double 类型时才会推出循环
4个数的和为100.0
4个数的平均值是25.0

Process finished with exit code 0

2. Sequential structure

The basic structure of Java is a sequential structure, unless otherwise specified, it will be executed sentence by sentence in order. Sequence structure is the simplest algorithm structure, between statements and statements, it is carried out in order from top to bottom, it is composed of several processing steps executed in sequence, it is an inseparable kind of any algorithm Basic Algorithmic Structure.

3. Choose structure

  • if single choice structure: We often need to judge whether something is feasible before we execute it. Such a process is represented by an if statement in the program
if(布尔表达式){
    
    
    // 如果布尔表达式为 true 将执行的语句
}
// 如果布尔表达式为假则直接跳过 if(){} 语句,执行下一个语句
package structure;

import java.util.Scanner;

public class ifDemo {
    
    
    public static void main(String[] args) {
    
    
        Scanner scanner = new Scanner(System.in);

        System.out.println("请输入内容:");
        String s = scanner.nextLine(); // 读取一行输入给 s

        // equals:判断字符串是否相等
        if (s.equals("Hello")){
    
    
            System.out.println(s);
        }

        System.out.println("End");
        scanner.close();
    }
}

// 输出界面如下
请输入内容:
Hello
Hello
End

Process finished with exit code 0
  • if double choice structure - choose one of the two
if(布尔表达式){
    
    
    // 如果布尔表达式为 true 将执行的语句
}
else{
    
    
    // 如果布尔表达式为 false 将执行的语句
}
package structure;

import java.util.Scanner;

public class ifDemo {
    
    
    public static void main(String[] args) {
    
    
        // 考试分数大于60就是及格,小于60就是不及格

        Scanner scanner = new Scanner(System.in);

        System.out.println("请输入成绩:");
        int score = scanner.nextInt(); // 读取成绩给 score

        // equals:判断字符串是否相等
        if (score >= 60){
    
    
            System.out.println("恭喜你及格了,成绩为" + score + "分");
        }
        else{
    
    
            System.out.println("很抱歉,你挂科了,成绩为" + score + "分");
        }
        System.out.println("End");
        scanner.close();
    }
}

// 输出界面如下
请输入成绩:
80
恭喜你及格了,成绩为80End

Process finished with exit code 0
  • if multiple choice structure - only one of the statements can be executed, and other statements are skipped directly
if(布尔表达式1){
    
    
    // 如果布尔表达式1为 true 将执行的语句
}
else if(布尔表达式2){
    
    
    // 如果布尔表达式2为 true 将执行的语句
}
else if(布尔表达式3){
    
    
    // 如果布尔表达式3为 true 将执行的语句
}
else if(布尔表达式4){
    
    
    // 如果布尔表达式4为 true 将执行的语句
}
...
package structure;

import java.util.Scanner;

public class ifDemo {
    
    
    public static void main(String[] args) {
    
    
        // 考试分数大于60就是及格,小于60就是不及格

        Scanner scanner = new Scanner(System.in);

        System.out.println("请输入成绩:");
        int score = scanner.nextInt(); // 读取成绩给 score

        // equals:判断字符串是否相等
        if (score==100){
    
    
            System.out.println("恭喜你是满分");
        }
        else if(score < 100 && score >=90){
    
    
            System.out.println("恭喜你成绩是A");
        }
        else if(score < 90 && score >=80){
    
    
            System.out.println("恭喜你成绩是B");
        }else if(score < 80 && score >=70){
    
    
            System.out.println("恭喜你成绩是C");
        }else if(score < 70 && score >=60){
    
    
            System.out.println("恭喜你成绩是D");
        }else if(score < 60 && score >=0){
    
    
            System.out.println("很遗憾你不及格");
        }
        else{
    
    
            System.out.println("输入不合法,请重新输入成绩(整数):");
        }
        System.out.println("End");
        scanner.close();
    }
}



// 输出界面如下
请输入成绩:
65
恭喜你成绩是D
End

Process finished with exit code 0

Notice

  1. An if statement has at most one else statement, and the else statement follows all else if statements .
  2. An if statement can have several else if statements, which must precede the else statement.
  3. Once one of the else if statements is detected as true, the other else if and else statements will skip execution.

4. switch multiple choice structure

Another way to implement the multiple choice statement is the switch case statement. The switch case statement judges whether a variable is equal to a certain value in a series of values. Each value is called a branch.

switch(expression){
    
    
    case value : // value 的变量类型可以是 byte、short、int 或者 char,现在可以比较字符串 String 了
        // 语句
        break; // 可选
    case value :
        // 语句
        break; // 可选
        // 你可以有任意数量的case语句
    default : // 可选
        // 语句
}
...

Develop a standard: add a break after each case statement to prevent penetration and execute too many statements.

package structure;

public class switchDemo {
    
    
    public static void main(String[] args) {
    
    
        // switch 匹配一个具体的值
        char grade = 'C';

        switch (grade){
    
    
            // case 穿透会从第一个匹配分支依次执行每个 case 直到遇到 break 或者 default
            case 'A':
                System.out.println("优秀");
                break; //可选
            case 'B':
                System.out.println("良好");
            case 'C':
                System.out.println("及格");
            case 'D':
                System.out.println("再接再厉");
            case 'E':
                System.out.println("不及格");
            default:
                System.out.println("重新输入");
        }
    }

}

// 输出界面如下
及格
再接再厉
不及格
重新输入

Process finished with exit code 0

5. while loop structure

  • while is the most basic loop, its structure is
while( 布尔表达式 ){
    
    
    // 循环内容
}
  • As long as the boolean value is true, the loop will continue to execute
  • In most cases, we will stop the loop, and we need a way to invalidate the expression to end the loop
  • A small number of cases need to be executed in a loop, such as server request response monitoring, etc.
  • If the loop condition is always true, it will cause an infinite loop
package structure;

public class whileDemo {
    
    
    public static void main(String[] args) {
    
    
        // 输出1~100

        int i = 0;
        // 每次循环都是先进行判断,表达式为 true 才执行循环体,如此往复
        while(i<100){
    
    
            i++;
            System.out.println(i);
        }
    }
}

6. do while loop

  • For the while statement, if the condition is not met, the loop cannot be entered. But sometimes we need to execute at least once even if the condition is not met
  • The do while loop is similar to the while loop except that the do while loop executes at least once
  • The difference between while and do while: while judges first and then executes, do while executes first and then judges; do while always ensures that the loop body is executed at least once
do{
    
    
    // 代码语句
}while(布尔表达式);

7. for loop

The for loop makes the loop structure simpler. The for loop is a general structure that supports iteration. It is the most effective and flexible. The number of executions of the for loop is determined before execution. The format is as follows:

for(初始化; 布尔表达式;更新){
    
    
    // 循环体
}
100.for // 快捷键 IDEA直接转化成100次的for循环,这是一种快捷方法,前面100可以改成任意数字

for(int i = 0; i < 100; i++) {
    
    
    
}

for(;;i++){
    
     // 死循环
    
}

[External link picture transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the picture and upload it directly (img-whn4DKNb-1633524465713)(.\Markdown_picture\for.100.png)]

Initialization steps are performed first. A type can be declared, but one or more loop control variables can be initialized, of course, it can also be an empty statement (using an existing variable as a loop control variable), and then, the value of the boolean expression is checked. If true, the loop body is executed. If it is false, the loop terminates, and the loop body is skipped to execute the following statements. After the loop body is executed once, the loop control variable must be updated, the Boolean expression is checked again, and the above process is executed cyclically.

package structure;

public class forDemo {
    
    
    public static void main(String[] args) {
    
    
        // 练习:计算0-100之间奇数和偶数的和
        int sumOdd = 0; // 奇数和
        int sumEven = 0; // 偶数和
        for(int i = 0; i <= 100;i++){
    
    

            if((i%2)==0){
    
     // 通过取余判断奇偶性,是偶数则对偶数和迭代
                sumEven = sumEven + i;
                System.out.println(i+"是偶数");

            }
            else{
    
     // 不满足偶数的 i 就是奇数了,更新奇数和
                sumOdd = sumOdd + i;
                System.out.println(i+"是奇数");
            }
        }
        System.out.println("偶数和为" + sumEven);
        System.out.println("奇数和为" + sumOdd);
    }
}

// 输出界面如下
......
99是奇数
100是偶数
偶数和为2550
奇数和为2500

Process finished with exit code 0
package structure;

public class forDemo {
    
    
    public static void main(String[] args) {
    
    
        // 练习:用 for 循环输出1-1000之间能被5整除的数,并且每行输出3个
        int count = 0; // 初始化输出计数变量为0
        for(int i = 1; i <= 1000;i++){
    
    
            if((i%5)==0){
    
     // 通过取余判断能否被5整除,只输出能被5整除的数
                // 控制每行输出3个数,新增一个计数变量 count,每当 count 被3整除时输出换行符
                count++;
                if(count%4 == 0){
    
     // 余数为1,2,3时输出,为0时输出空行
                    System.out.println(); // 每隔3个数输出一个空行
                }
                else{
    
    
                    System.out.print(i+"\t");
                }
            }
        }
    }
}

// 输出界面如下
......
945 950 955 
965 970 975 
985 990 995 

Process finished with exit code 0

insert image description here

package structure;

public class forDemo {
    
    
    public static void main(String[] args) {
    
    
        // 练习:打印九九乘法表

        for(int i = 1; i <= 9;i++){
    
     // 外层循环9次,循环控制变量 i 同时作为右乘数
            for(int j = 1; j <= i; j++){
    
     // 内层循环 j 次,循环控制变量 j 同时作为左乘数,j <= i形成下三角的乘法表
                System.out.print(j+"x"+i+"="+(i*j)+"\t"); // 输出乘法公式 i x j = i*j
            }
            System.out.println(); // 每一行执行完后换行
        }
    }
}

// 输出界面如下
1x1=1	
1x2=2	2x2=4	
1x3=3	2x3=6	3x3=9	
1x4=4	2x4=8	3x4=12	4x4=16	
1x5=5	2x5=10	3x5=15	4x5=20	5x5=25	
1x6=6	2x6=12	3x6=18	4x6=24	5x6=30	6x6=36	
1x7=7	2x7=14	3x7=21	4x7=28	5x7=35	6x7=42	7x7=49	
1x8=8	2x8=16	3x8=24	4x8=32	5x8=40	6x8=48	7x8=56	8x8=64	
1x9=9	2x9=18	3x9=27	4x9=36	5x9=45	6x9=54	7x9=63	8x9=72	9x9=81	

Process finished with exit code 0

Enhanced for loop

Mainly used to traverse arrays and collections, and will be used frequently later

for(声明语句 : 表达式){
    
     
    // 代码语句
}
  • Declaration statement: declare a new local variable, the variable type must match the type of the array element, the scope is limited in the loop statement, and its value is equal to the value of the array element at this time
  • Expression: An expression is the name of the array to be accessed, or a method that returns an array
package structure;

public class forDemo {
    
    
    public static void main(String[] args) {
    
    
        int[] numbers = {
    
    10,20,30,40,50}; // 定义了一个数组
        // 遍历数组的元素 迭代器
        for(int x:numbers){
    
    
            System.out.println(x);
        }
    }
}

// 输出界面如下
10
20
30
40
50

Process finished with exit code 0

break contuine

  • break In the body of any loop statement, you can use break to control the flow of the loop. break is used to forcibly exit the loop without executing the remaining statements in the loop (jump out of the entire loop body)
  • The continue statement is used in the loop statement body to terminate a certain loop process, that is, to jump out of the statement that has not been executed in the loop body, and then to determine whether to execute the loop next time (only one loop iteration is skipped)
package structure;

public class forDemo {
    
    
    public static void main(String[] args) {
    
    
        // 打印三角形 5行
        for (int i = 1; i <= 5; i++) {
    
     // 先分解为5行,每一行先输出(5-i)个空格和 2i 个*
            int count = 5 - i; // 每一行的空格数目
            for (int j = 0; j < count; j++) {
    
     // 先输出空格
                System.out.print(" ");
            }
            for (int k = 1; k <= (2*i-1); k++) {
    
     // 再输出星星
                System.out.print("*");
            }
            System.out.println(); // 换行
        }
    }
}

// 输出界面如下
    *
   ***
  *****
 *******
*********

Process finished with exit code 0

java method

1. What is the method?

  • What is the specific meaning of sout-> System.out.println()? Among them, System is a class, so System.out is actually a standard output object out of the System class, and finally println() is a method, which belongs to the object and is generally defined in the class.
  • A method is a collection of statements that together perform a function. A method is an ordered combination of steps to solve a class of problems. The method is contained in a class or object, and the method is created in the program and referenced elsewhere.
  • The principle of design method: The original meaning of a method is a function block, which is a collection of statement blocks that realize a certain function. When we design a method, it is best to keep the atomicity of the method, that is, a method only completes one function, which is conducive to later expansion
package method;

public class demo01 {
    
    
    // main 方法只是一个致敬,并不是必须从main函数开始执行
    public static void main(String[] args) {
    
    
        int sum = add(5,4);
        System.out.println(sum);

    }
    public static int add(int a, int b){
    
     // static的目的是使add变成全局作用域
        return a+b;
    }
}

2. Method definition and call

method definition

Java methods are similar to functions in other languages. They are code fragments used to complete specific functions. In general, defining a method includes the following syntax:

A method consists of a method header and a method body.

修饰符 返回值类型 方法名(参数类型 参数名...){
    
    
    ...
    方法体
    ...
    return 返回值;
}

Here are all the parts of a method:

  • Modifier: optional, tells the compiler how to call the method, defines the access type of the method

  • Return value type: The method may have a return value, returnValueType is the data type of the method return value. Some methods perform the desired operation, but have no return value, in which case returnValueType is void

  • Method name: the actual name of the method, the method name and the parameter table together form the method signature

  • Parameter type: The parameter is like a placeholder, when the method is called, the value is passed to the parameter. This value is called an actual parameter or variable. The parameter list refers to the parameter type, order and number of parameters of the method. Parameters are also optional, and methods can contain no parameters.

    Formal parameters - Placeholders that are newly created on the stack to receive actual parameters when a method is called. Actual parameters - the data actually passed to the method when the method is called

  • Method body: The method body contains specific execution statements and defines the function of the method

    package method;
    
    public class demo01 {
          
          
        // main 方法只是一个致敬,并不是必须从main函数开始执行
        public static void main(String[] args) {
          
          
            int maxNumber = max(5,4);
            System.out.println(maxNumber);
    
        }
    
        // 两个整数比大小,取最大值
        public static int max(int a, int b){
          
          
            if(a>=b){
          
          
                return a;
            }
            else{
          
          
                return b;
            }
        }
    }
    
    // 输出界面如下
    5
    
    Process finished with exit code 0
    

    method call

    • Call method: object name. method name (actual parameter list)

    • Java supports two ways to call methods, choose according to whether the method returns a value

    • But when the method returns a value, the method call is usually treated as a value. For example: int larger = max(30, 40);

    • If the method return value is void, the method call must be a statement. For example: System.out.println("Hello World")

      Java is all pass by value, no pass by reference

3. Method overloading

  • Overloading is a method in a class that has the same function name but different parameters .
  • Rules for method overloading: method names must be the same; parameter lists must be different; method return value types can be the same or different; just different return types are not enough to become method overloading
  • Implementation theory: When the method names are the same, the compiler will match one by one according to the number of parameters and parameter types of the calling method to select the corresponding method. If the matching fails, the compiler will report an error

4. Command line parameters

Sometimes you want to pass a message to a program when you run it. This is achieved by passing command line parameters to the main() function

package method;

public class commandLine {
    
    
    public static void main(String[] args) {
    
    
        // args.length 数组长度
        for(int i = 0; i < args.length; i++){
    
    
            System.out.println("args["+i+"]"+args[i]);
        }
    }
}
Microsoft Windows [版本 10.0.19043.928]
(c) Microsoft Corporation。保留所有权利。

E:\Study\Windows工作文件\2021.9\Java从零开始\src\method>javac commandLine.java	// 文件夹下面会编译多出一个class文件

E:\Study\Windows工作文件\2021.9\Java从零开始\src\method>cd ..	// 此时必须退回到src文件夹下,因为class文件有依赖关系

E:\Study\Windows工作文件\2021.9\Java从零开始\src>java method.commandLine	// 其实class文件已经运行,只是我们没有给main传参

E:\Study\Windows工作文件\2021.9\Java从零开始\src>java method.commandLine this is shit	// this is shit 被当作2个string参数
args[0]this
args[1]is
args[2]shit

5. Variable parameters

  • Beginning with JDK1.5, Java supports passing variable parameters of the same type to a method. In the method declaration, add an ellipsis (…) after the specified parameter type.

  • Only one variable parameter can be specified in a method, it must be the last parameter of the method , any normal parameter must be declared before it.

  • Detailed in the array

    package method;
    
    public class commandLine {
          
          
        public static void main(String[] args) {
          
          
            commandLine test = new commandLine();
            test.printMax(1,2,5,6,45,222.0);
            }
            public static void printMax(double... numbers){
          
          
            // 健壮性测试
            if(numbers.length == 0){
          
          
                System.out.println("No argument passed");
                return;
            }
    
            double result = numbers[0];
            // 排序
            for(int i = 1; i < numbers.length; i++){
          
          
                if(numbers[i] > result){
          
          
                    result = numbers[i];
                }
            }
            System.out.println("The max value is " + result);
        }
    }
    
    // 输出界面如下
    The max value is 222.0
    
    Process finished with exit code 0
    

6. Recursion

  • Recursion is: A method calls A method! just call yourself

  • Recursion can be used to solve some complex problems with simple programs. It usually converts a large and complex problem layer by layer into a smaller-scale problem similar to the original problem to solve. The recursive strategy only needs a small number of programs to describe the multiple repeated calculations required for the problem-solving process, greatly reducing The amount of code in the program. The power of recursion lies in the use of finite statements to define an infinite collection of objects

  • A recursive structure consists of two parts:

    Recursive header: When not calling its own method, if there is no header, it will fall into an infinite loop

    Recursive body: when do you need to call your own method

Recursion can be used when the base is small. When the base is large, the function will be called too many times, and the stack will be exhausted, resulting in memory overflow and failure to execute. So try to use iterative methods instead of recursion

package method;

public class demo02 {
    
    
    // 阶乘 n!
    public static void main(String[] args) {
    
    
        System.out.println(func(5)); // 超过50就溢出,结果就是0 
    }
    public static int func(int n){
    
    
        // 递归头提出退出递归的条件:边界条件
        if(n == 1){
    
    
            return 1;
        }else{
    
    
            return n*func(n-1);
        }
    }
}
// 输出界面如下
120

Process finished with exit code 0

package method;

import java.util.Scanner;

// 设计一个计算器,能一直算的那种
public class computer {
    
    
    public static void main(String[] args) {
    
    
        Scanner scanner = new Scanner(System.in); // 读入键盘上的输入
        System.out.println("请输入ENTER进入计算,想结束程序请输入EXIT");
        while(scanner.nextLine()!="EXIT") {
    
    
            System.out.println("请输入第一个整数:");
            int number1 = scanner.nextInt(); // 用于接收键盘上的第一个操作数
            System.out.println("请输入操作符+ - * /");
            String operator = scanner.next();
            System.out.println("请输入第二个整数:");
            int number2 = scanner.nextInt(); // 用于接收键盘上的第二个操作数

            // 主体是Switch结构选择方法
            switch (operator) {
    
    
                case "+":
                    System.out.println(add(number1, number2));
                    break;
                case "-":
                    System.out.println(sub(number1, number2));
                    break;
                case "*":
                    System.out.println(multi(number1, number2));
                    break;
                case "/":
                    System.out.println(div(number1, number2));
                    break;
                default:
                    System.out.println("输入错误!");
            }
        }
        scanner.close();

    }
    public static int add(int a, int b){
    
    
        return a + b;
    }
    public static int sub(int a, int b){
    
    
        return a - b;
    }
    public static int multi(int a, int b){
    
    
        return a * b;
    }
    public static int div(int a, int b){
    
    
        return a / b;
    }
}

java array

1. Array overview

array definition

An array is an ordered collection of data structures of the same type. An array describes several data of the same type, which are arranged and combined in a certain order. Each data is called an array element, and each array element can be passed through a icon to access them.

2. Array declaration creation

Array variables must first be declared before the array can be used in the program. Following is the syntax for declaring array variables:

dataType[] arrayRefVar; // 首选的方法
dataType arrayRefVar[]; // 效果相同,但不是首选的方法

The Java language uses the new operator to create arrays, the syntax is as follows:

dataType[] arrayRefVar = new dataType[arraySize];

The elements of the array are accessed through the index index, the array index starts from 0, and the length of the array is obtained: array.length

memory analysis

Java memory analysis:

  1. Heap area: stores new objects and arrays, can be shared by all threads, and will not store other object references
  2. Stack area: store the basic variable type (including the specific value of this basic type), the variable of the reference object (store the specific address of this reference in the heap)
  3. Method area: can be shared by all threads, including all class and static variables

Corresponding to the creation process of the array, we bring it into the inside of the stack here

int[] numbers; // 1.声明一个数组,在栈区新建一个“指针”,但没有初始化为随机值,准备指向数组的内存地址
numbers = new int[5]; // 2.创建数组,用 new 给数组在堆区分配了5个 int 的空间,并把地址给到前面的“指针”

numbers[0] = 5; // 3.声明后只能通过下标给数组元素赋值,相当于直接对堆区的每一个 int 空间进行赋值操作
numbers[1] = 15;
numbers[2] = 20;
numbers[3] = 25;
numbers[4] = 30;

insert image description here

Three kinds of initialization

Static initialization; dynamic initialization; array default initialization (array is a reference type, and its elements are equivalent to instance variables of the class, so once the array is allocated space, each element in it is also implicitly initialized in the same way as instance variables)

package array;

public class demo02 {
    
    
    public static void main(String[] args) {
    
    
        // 静态初始化:创建 + 赋值
        int[] a = {
    
    1, 2, 3};
        System.out.println(a[2]);
        // 动态初始化:包含默认初始化
        int[] b = new int[10]; // 此时数组元素均为0
        b[0] = 10;
        System.out.println(b[0]);
        System.out.println(b[1]); // 默认初始化为0
    }
}
// 输出界面如下
3
10
0

Process finished with exit code 0

4 basic characteristics of arrays

  • Its length is fixed, and once the array is created, its size cannot be changed
  • Array elements must be of the same type, mixed types are not allowed
  • The elements in the array can be of any data type, including primitive types and reference types
  • Array variables belong to the reference type, and arrays can also be regarded as objects. Each element in the array is equivalent to a member variable of the object. The array itself is an object, and the object in Java is in the heap, so whether the array saves the original type or other object types, the array object itself is in the heap

array bounds

The legal range of the subscript: [0, length-1], if it exceeds the limit, an error will be reported ArrayIndexOutOfBoundsException: Array subscript out of bounds exception!

Summary: 1. An array is an ordered collection of the same data type 2. An array is also an object, and the elements of the array are equivalent to the member variables of the object 3. The length of the array is fixed and immutable. If it exceeds the limit, an error will be reported.

3. Array use

  • for-each loop

    package array;
    
    public class demo02 {
          
          
        public static void main(String[] args) {
          
          
            int[] arrays = {
          
          1, 2, 3, 4, 5};
            // 遍历打印全部数组元素
            for (int i = 0; i < arrays.length; i++) {
          
          
                System.out.println(arrays[i]);
            }
            System.out.println("===============");
            // 计算所有元素的和
            int sum = 0;
            for (int i = 0; i < arrays.length; i++) {
          
          
                sum += arrays[i];
            }
            System.out.println("数组元素和为:"+sum);
            System.out.println("===============");
            // 查找最大元素
            int max = arrays[0];
            for (int i = 0; i < arrays.length; i++) {
          
          
                if(arrays[i] > max){
          
          
                    max = arrays[i];
                }
            }
            System.out.println("数组最大元素为:"+max);
        }
    }
    // 输出界面如下
    1
    2
    3
    4
    5
    ===============
    数组元素和为:15
    ===============
    数组最大元素为:5
    
    Process finished with exit code 0
    
    package array;
    
    public class demo03 {
          
          
        public static void main(String[] args) {
          
          
            int[] arrays = {
          
          1, 2, 3, 4, 5};
            // JDK1.5开始支持,不用下标使用迭代器遍历数组,和Python一样适合打印但不适合下标操作
            for(int array:arrays){
          
          
                System.out.println(array);
            }
        }
    }
    // 输出界面如下
    1
    2
    3
    4
    5
    
    Process finished with exit code 0
    
  • Array as method input parameter

    package array;
    
    public class demo03 {
          
          
        public static void main(String[] args) {
          
          
            int[] arrays = {
          
          1, 2, 3, 4, 5};
            // JDK1.5开始支持,不用下标使用迭代器遍历数组,和Python一样适合打印但不适合下标操作
            printArray(arrays);
        }
        // 通过使用方法调用将数组当作参数传入
        public static void printArray(int[] arrays){
          
          
            for(int array:arrays){
          
          
                System.out.println(array);
            }
        }
    }
    // 输出界面如下
    1
    2
    3
    4
    5
    
    Process finished with exit code 0
    
  • array as return value

    package array;
    
    public class demo03 {
          
          
        public static void main(String[] args) {
          
          
            int[] arrays = {
          
          1, 2, 3, 4, 5};
            // JDK1.5开始支持,不用下标使用迭代器遍历数组,和Python一样适合打印但不适合下标操作
            printArray(reverseArray(arrays));
        }
        // 打印数组
        public static void printArray(int[] arrays){
          
          
            for(int array:arrays){
          
          
                System.out.println(array);
            }
        }
        // 翻转打印数组
        public static int[] reverseArray(int[] arrays){
          
          
            int[] reverse = new int[arrays.length]; // 新建同样大小数组用于接收原数据
            // 进行元素收尾对调
            for (int i = 0; i < arrays.length; i++) {
          
          
                reverse[arrays.length-i-1] = arrays[i]; //即大小为5的话,r[4]=a[0],记住-1
            }
            return reverse;
        }
    }
    // 输出界面如下
    5
    4
    3
    2
    1
    
    Process finished with exit code 0
    

4. Multidimensional array

A multidimensional array can be regarded as an array of arrays. For example, a two-dimensional array is a special array in which each element is a one-dimensional array. By analogy, it can be extended to multidimensional arrays, and nested arrays can be

int a[][] = new int[2][5]; // 2行5列的数组,想象成一个链表一样的int[2]是个数组元素是指针指向另一个int[5]的数组首地址

5. Arrays class

  • The utility class java.util.Arrays of the array, because the array object itself has no declared method for us to call, but a utility class Arrays is provided in the API for us to use, so that we can perform some basic operations on the data object. Pay attention to check the JDK help documentation. The methods in the Arrays class are all statically modified static methods, which can be called directly using the class name when in use, and "don't" use the object to call (note: it is not necessary but not impossible)

  • Has the following common functions:

    Assigning values ​​to an array: the fill method

    Sort an array: the sort method, in ascending order

    Comparing arrays: equals method, compares whether the element values ​​in the array are equal

    Find array elements: binarySearch method can perform binary search on sorted arrays

package array;


import java.util.Arrays;

public class demo04 {
    
    
    public static void main(String[] args) {
    
    
        int[] array = {
    
    25, 333, 254, 64, 128};
        // 打印数组元素
        System.out.println(array); // [I@49e4cb85
        // 打印数组元素 Arrays.toString
        System.out.println(Arrays.toString(array));
        // 升序排序
        Arrays.sort(array);
        System.out.println(Arrays.toString(array));
        
        Arrays.fill(array, 20);// 使用20来填充每一个数组元素 
        System.out.println(Arrays.toString(array));
    }
}
// 输出界面如下
[I@49e4cb85
[25, 333, 254, 64, 128]
[25, 64, 128, 254, 333]
[20, 20, 20, 20, 20]

Process finished with exit code 0

Bubble Sort

Bubble sort is undoubtedly one of the most famous sorting algorithms, with a total of eight sorts. The code of bubble sorting is quite simple, with two layers of loop nesting, the outer layer records the number of bubbles, and the inner layer compares the minimum value in turn. The time complexity is O(n^2)

package array;

import java.util.Arrays;

public class demo05 {
    
    
    public static void main(String[] args) {
    
    
        int[] a = {
    
    1,5161,11,2457,1346,1846,32,466,55};
        int[] sort = sort(a);
        System.out.println(Arrays.toString(sort));
    }
    // 冒泡排序方法
    public static int[] sort(int[] array){
    
    
        // 外层循环判断走多少次
        for (int i = 0; i < array.length - 1; i++) {
    
    
            // 内层循环比较两个数,每次把最大的数排到最左侧
            for (int j = 0; j < array.length - 1 - i; j++) {
    
    
                // 内层循环比大小,因为外层循环了 i 次所以确定了 i 个数,所以循环次数为 array.length - 1 - i
                if(array[j] < array[j+1]){
    
    
                    // 通过中间杯子交换两个数
                    int temp = array[j];
                    array[j] = array[j+1];
                    array[j+1] = temp; // 相邻两个数组元素交换完毕
                }
            }
        }
        return array;
    }
}
// 输出界面如下
[5161, 2457, 1846, 1346, 466, 55, 32, 11, 1]

Process finished with exit code 0

6. Sparse Arrays

When most elements in an array are 0, or an array of the same value, you can use a sparse array to save the array. The processing method of the sparse array is: record how many rows and columns the array has, and how many different values ​​there are; record elements with different values, rows, columns and values ​​in a small-scale array, thereby reducing the size of the program.

package array;

public class demo06 {
    
    
    public static void main(String[] args) {
    
    
        // 1.创建一个二维数组 11*11 0:没有棋子  1:黑棋  2:白棋
        int[][] array = new int[11][11]; // 新建二维数组,默认值为0
        array[1][2] = 1;
        array[2][3] = 2;
        // 输出原始数组
        System.out.println("输出原始数组:");
        for (int[] ints : array) {
    
    
            for (int anInt : ints) {
    
    
                System.out.print(anInt + "\t");
            }
            System.out.println();// 打印一行后换行
        }
        System.out.println("=========================================");
        // 转换为稀疏数组保存,先获取有效值的个数
        int sum = 0;
        for (int i = 0; i < 11; i++) {
    
    
            for (int j = 0; j < 11; j++) {
    
    
                if(array[i][j] != 0){
    
    
                    sum++;
                }
            }
        }
        System.out.println("有效值的个数:" + sum);

        // 创建一个稀疏数组
        int[][] newArray = new int[sum+1][3];
        newArray[0][0] = 11;// 表头几行几列几个有效值
        newArray[0][1] = 11;
        newArray[0][2] = sum;
        // 遍历二维数组,将非 0 值存放在稀疏数组
        int count = 0;
        for (int i = 0; i < array.length; i++) {
    
    
            for (int j = 0; j < array.length; j++) {
    
    
                if(array[i][j] != 0){
    
    
                    count++; // 计数加换行的作用
                    newArray[count][0] = i; // 先存行号
                    newArray[count][1] = j; // 再存列号
                    newArray[count][1] = array[i][j]; // 再存值大小
                }
            }
        }
        System.out.println("输出稀疏数组:");
        for (int[] ints : newArray) {
    
    
            for (int anInt : ints) {
    
    
                System.out.print(anInt + "\t");
            }
            System.out.println();// 打印一行后换行
        }
    }
}
// 输出界面如下
输出原始数组:
0	0	0	0	0	0	0	0	0	0	0	
0	0	1	0	0	0	0	0	0	0	0	
0	0	0	2	0	0	0	0	0	0	0	
0	0	0	0	0	0	0	0	0	0	0	
0	0	0	0	0	0	0	0	0	0	0	
0	0	0	0	0	0	0	0	0	0	0	
0	0	0	0	0	0	0	0	0	0	0	
0	0	0	0	0	0	0	0	0	0	0	
0	0	0	0	0	0	0	0	0	0	0	
0	0	0	0	0	0	0	0	0	0	0	
0	0	0	0	0	0	0	0	0	0	0	
=========================================
有效值的个数:2
输出稀疏数组:
11	11	2	
1	1	0	
2	2	0	

Process finished with exit code 0

Java object-oriented programming

The core idea of ​​Java is OOP

1. Getting to know object-oriented

  • Process-oriented thinking: the steps are clear and simple, what to do in the first step, and what to do in the second; process-oriented is suitable for dealing with some relatively simple problems

  • Object-oriented thinking: things flock together, the way of thinking of classification , thinking about the problem will first solve the problem which classification is needed, and then think about these classifications separately. Finally, process-oriented thinking is carried out on the details under a certain category; object-oriented is suitable for dealing with complex problems, and is suitable for dealing with problems that require multi-person cooperation!

  • For describing complex things, in order to grasp and analyze from a macro perspective, we need to use object-oriented thinking to analyze the entire system. However, when it comes to specific micro-operations, a process-oriented approach is still required.

    So it doesn't mean that object-oriented is better than process-oriented. This is the same as deep learning and traditional programming, but which one is more suitable for different problems. In the face of simple and thin problems, process-oriented can handle them well; in the face of complex and huge problems, object-oriented methods can be used to break them into parts, so as not to be confused and extract good results from complex problems. The characteristics thus flock together and break down one by one.

    property + method = class

what is object oriented

  • Object-Oriented Programming (OOP), the essence of object-oriented programming is to organize code in the form of classes and organize (encapsulate) data in the form of objects.

  • Three major features: encapsulation (limitation of authority); inheritance (reduction of duplication); polymorphism (multiple forms)

  • From an epistemological point of view, there are objects first and then classes. Objects are concrete things. A class is an abstraction of an object

  • From the perspective of code operation, there are classes first and then objects, and classes are the templates of objects.

2. Method review and deepening

method definition

  • Modifier: public static guarantees global access
  • Return type: consistent with the return value type
  • The difference between break and return: one is to exit the current loop body, the other is to exit the current function body
  • Method name: hump principle, see the name and know the meaning
  • parameter list: parameter list, parameter name
  • Exception throwing: finally explained in oop

method call

  • Static method: static , it is loaded with the class very early, so it can be called directly in the main function
package oop;

public class demo01 {
    
    
    public static void main(String[] args) {
    
    
        Student.say(); // 在静态方法调用时直接用类方法就可以进行调用

    }
}
// 输出界面如下
学生说话了

Process finished with exit code 0
    
package oop;

public class Student {
    
    
    public static void say(){
    
    
        System.out.println("学生说话了");
    }
}
  • Non-static methods are loaded only when the class is instantiated
package oop;

public class demo01 {
    
    
    public static void main(String[] args) {
    
    
        // 对象类型 对象名 = 对象值;
        Student student = new Student(); // 在非静态方法调用时需要实例化对象后调用
		student.say();
    }
}
// 输出界面如下
学生说话了

Process finished with exit code 0
    
package oop;

public class Student {
    
    
    public static void say(){
    
    
        System.out.println("学生说话了");
    }
}

Therefore, when one class is static and the other is not, they cannot call each other, because the non-static class has not been loaded yet

  • Formal Participation Arguments
package oop;

public class demo02 {
    
    
    public static void main(String[] args) {
    
    
      	int a = 1; // 与change方法内 int a 同名不同命,实际是两个内存地址
        System.out.println(a);
        
        demo02.change(a);
		System.out.println(a);
    }
    // 返回值为空,仅进行方法体
    public static void change(int a) {
    
    
        int a = 10; // 作用域有限,仅在方法内有效,方法结束后就被释放了
    }
}
// 输出界面如下
1
1

Process finished with exit code 0

  • Passing by value and passing by reference: passing by value does not change the original value, while passing by reference changes both
package oop;

public class demo02 {
    
    
    public static void main(String[] args) {
    
    
        Person person = new Person(); // 实例化
        System.out.println(person.name);

        demo02.changeName(person);
        System.out.println(person.name);


    }
    public static void changeName(Person a){
    
    
        a.name = "Marine";
    }
}

class Person{
    
    
    String name; // 默认是null
}
// 输出界面如下
null
Marine

Process finished with exit code 0
  • this keyword

3. Object creation analysis

class and object relationship

A class is an abstract data type. It is an overall description/definition of a certain type of thing, but it cannot represent a specific thing. These classes are used to describe the characteristics and behaviors that a certain type of specific things should have.

An object is a concrete instance of an abstract concept, and it is a concrete instance, not an abstract concept, that can embody characteristics and functions.

Create and initialize objects

  • Objects are created using the new keyword

Main function class (one program can only have one)

package oop.application;

// 一个项目应该只有一个 main 方法
public class Application {
    
    

    public static void main(String[] args) {
    
    
        // 类是抽象的,需要实例化一个个体
        // 类实例化后会返回一个自己类的对象
        Student Jack = new Student(); // 这里的 Student() 其实就是学生类的一个同名构造函数,系统自动生成
        Student Brand = new Student();
        Jack.age = 15;
        Jack.name = "Jack";
        Brand.name = "Brand";
        Brand.age = 16;
        System.out.println(Jack.name+"今年"+Jack.age+"岁");
        System.out.println(Brand.name+"今年"+Brand.age+"岁");
    }
}
// 输出界面如下
Jack今年15Brand今年16Process finished with exit code 0

member class

package oop.application;

// 学生类
public class Student {
    
    
    // 属性
    String name;
    int age;

    // 方法
    public void study(){
    
    
        System.out.println(this.name + "学生在学习"); // this 代表当前这个类,this.name 则是当前类的name属性
    }

}

  • When using the new keyword to create, in addition to allocating memory space, the created object will be initialized by default and the constructor in the class will be called

  • A constructor in a class is also called a constructor, which must be called when creating an object. And the constructor has the following two characteristics:

    1. Must be the same as the class name 2. Must have no return type, and void cannot be written

Even if a class doesn’t write anything, it still has a method—the construction method; of course, you can also explicitly write the construction method to limit the initial value.

package oop.application;

public class Person {
    
    
    String name;

    // 显示定义无参构造方法
    public Person(){
    
    
        this.name = "Marine"; // 显示赋初始值为 Marine
    }
    // 有参构造方法:一旦定义了有参构造,无参构造就必须显示定义,否则就无效
    public Person(String name){
    
    
        this.name = name; // this.name 的name是对象的属性,而 String name 的name是形参
    }
}
package oop.application;

// 一个项目应该只有一个 main 方法
public class Application {
    
    

    public static void main(String[] args) {
    
    
        // 类是抽象的,需要实例化一个个体
        // 1.使用 new 关键字时,本质是调用构造器
        // 2.初始化值
        Person person = new Person(); 
        System.out.println(person.name); // 此时优先调用用户定义的显示构造方法
    }
}
// 输出界面如下
Marine

Process finished with exit code 0

[External link picture transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the picture and upload it directly (img-0C3A6VT6-1633524465715)(.\Markdown_Picture\alt+insert)]

package oop.application;
// 使用 alt + insert 快速添加构造器
public class Person {
    
    
    String name;

    public Person() {
    
    
    }

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

summary

  • Constructor: 1. Same as class name 2. No return type
  • Function: 1. When using the new keyword, the essence is to call the constructor 2. Initialize the value of the object
  • Points to note: 1. After defining a parameterized construction method, if you want to use a parameterless construction, you must display the definition, otherwise it will be invalid. 2. Shortcut key ALT + INS, create a constructor 3. this points to the current class, which is often used inside the class definition
    insert image description here

The main function runs in the stack area, and the heap area includes the method area and object instance area, etc. The static method area is the modifier static that we have been using for convenience, because it has the feature of being loaded with the class and can be called directly in the class. ——Stack area: used by programs; heap area: used by programmers

insert image description here

In fact, the newly created objects in the main function are all reference variables, and the heap area where the object actually exists in the memory is initialized by inheriting the method of the class in the method area, such as shout(), and calling the constructor. Subsequent operations on objects in the main function are also changes to the corresponding memory in the heap.

4. Three major characteristics of object-oriented

encapsulation

  • What should be hidden should be hidden

    Program design requires the pursuit of **"high cohesion, low coupling"**. High cohesion means that the internal data operation details of the class are completed by itself, and no external interference is allowed; low coupling means that only a small number of methods are exposed for external use.

  • Encapsulation (hiding of data)

    In general, direct access to the actual representation of data in an object should be prohibited, and should be accessed through the operational interface, which is called information hiding

  • Remember that the property is private, get/set can only perform limited operations on the private property in the class through the open method get/set.

package oop.application;

// 学生类
public class Student {
    
    
    // 私有属性
    private String name; // 姓名
    private int ID; // 学号
    private int age; // 年龄
    private char sex; // 性别

    // 提供外部能使用的方法
    // get获得这个数据
    public String getName(){
    
    
        return this.name;
    }
    // set设置这个数据
    public void setName(String name){
    
    
        this.name = name;
    }

}
package oop.application;

// 一个项目应该只有一个 main 方法
public class Application {
    
    

    public static void main(String[] args) {
    
    
        // 类是抽象的,需要实例化一个个体
        Student student1 = new Student();
        System.out.println(student1.getName());
        student1.setName("Marine");
        System.out.println(student1.getName());
    }
}
// 输出界面如下
null
Marine

Process finished with exit code 0

Benefits: 1. Improve program security and protect data 2. Hidden code implementation details 3. Unified interface 4. System maintainability

inherit

The essence of inheritance is the abstraction of a certain group of classes, so as to achieve better modeling of the real world. extends means "extends", and a subclass is an extension of a parent class. Classes in Java only have single inheritance, not multiple inheritance!

Inheritance is a relationship between classes and classes. In addition, the relationship between classes and classes includes dependency, composition, aggregation, etc. There are two classes in the inheritance relationship, one is the subclass (derived class) and the other is the parent class (base class). The subclass inherits from the parent class, which is represented by the keyword extends. There should be an "is a" relationship between the subclass and the parent class in a sense.

package oop.demo03;

public class Person {
    
    
    public int money = 10_0000_0000; // 财产10亿,属性最好私有get方法访问
    public void say(){
    
    
        System.out.println("Person说了一句话");
    }
}
package oop.demo03;
// 学生 is 人:派生类,子类
// 子类继承了父类,就会拥有父类的全部方法和属性
public class Student extends Person{
    
    
}
package oop.demo03;

public class Application {
    
    
    public static void main(String[] args) {
    
    
        Student student = new Student();
        student.say();
        System.out.println(stuednt.money);
    }
}
// 输出界面如下
Person说了一句话
1000000000
    
Process finished with exit code 0

The four priorities of permissions are from low to high: public–>protected–>default–>private

insert image description here

Press CTRL + h in the class to display the inheritance tree information in the right column. All classes inherit the Object class directly or indirectly by default, and some methods are built into it.

super

In contrast, the this pointer points to the current class, and super points to the parent class of the current class, so that some open properties and methods in the parent class can be accessed.

package oop.demo03;

public class Person {
    
    
    protected String name = "Person";
}
package oop.demo03;

public class Student extends Person{
    
    
    public String name = "Student";

    public void test(String name){
    
    
        System.out.println(name); // Marine,形参的值
        System.out.println(this.name); // Student,指向当前类的 name 属性
        System.out.println(super.name); // Person,指向父类的 name 属性
    }
}
package oop.demo03;

public class Application {
    
    
    public static void main(String[] args) {
    
    
        Student student = new Student();
        student.test("Marine");
    }
}
// 输出界面如下
Marine
Student
Person

Process finished with exit code 0

By default, the subclass object constructor calls the parent class constructor first.

package oop.demo03;

public class Person {
    
    
    public Person(){
    
    
        System.out.println("Person无参构造函数");
    }
}
package oop.demo03;

public class Student extends Person{
    
    
    public Student(){
    
    
        // 隐藏代码:调用了父类的无参构造函数
        super(); // super() 默认用来调用父类构造器,必须在子类构造器第一行
        System.out.println("Student无参构造函数");
    }
}
package oop.demo03;

public class Application {
    
    
    public static void main(String[] args) {
    
    
        Student student = new Student();

    }
}
// 输出界面如下
Person无参构造函数
Student无参构造函数

Process finished with exit code 0

super summary

  1. super calls the constructor of the parent class, must be the first in the constructor
  2. super must only appear in subclass methods or constructors
  3. super and this cannot appear in the constructor at the same time (both must be on the first line)

VS this:

The objects represented are different: this points to the object of the caller itself; super points to the reference of the parent class object

The premise is different: this can be used without inheritance; super can only be used under the condition of inheritance

The construction method is different: this calls the construction method of this class; super calls the construction method of the parent class

method override

Rewriting is method rewriting has nothing to do with attributes, and rewriting methods are related to static or non-static methods

static method:

package oop.demo04;

public class A extends B{
    
    
    public static void test(){
    
    
        System.out.println("A=>test()");
    }
}
package oop.demo04;

public class B {
    
    
    public static void test(){
    
    
        System.out.println("B=>test()");
    }
}
package oop.demo04;

public class Application {
    
    
    public static void main(String[] args) {
    
    
        // 方法的调用只和左边,定义的数据类型有关
        A a = new A(); // a 的数据类型是 A
        a.test();
        // 父类的引用可以指向子类
        B b = new A(); // b 的数据类型是 B
        b.test();
    }
}
// 输出界面如下
A=>test()
B=>test()
    
Process finished with exit code 0

Non-static method:

package oop.demo04;

public class A extends B{
    
    
    // Override 重写
    @Override // 注解:有功能的注释!
    public void test(){
    
    
        System.out.println("A=>test()");
    }
}
package oop.demo04;

public class B {
    
    
    public void test(){
    
    
        System.out.println("B=>test()");
    }
}
package oop.demo04;

public class Application {
    
    
    
    // 静态方法和非静态方法区别很大!
    public static void main(String[] args) {
    
    
        
        A a = new A(); 
        a.test();
        // 父类的引用可以指向子类
        B b = new A(); // 子类重写了父类的方法
        b.test();
    }
}
// 输出界面如下
A=>test()
A=>test()
    
Process finished with exit code 0

Rewriting summary: The premise is that there is an inheritance relationship, and the subclass must override the parent class method!

  1. method names must be the same
  2. The parameter list is also the same (otherwise it is overloaded)
  3. Modifier: The scope can be expanded; it can be extended from the private method of the parent class to the public method of the subclass. public–>protected–>default–>private
  4. Exception thrown: Scope can be narrowed but not widened.

For rewriting, the method name of the subclass must be consistent with that of the parent class, and the method body is different!

Why do you need to rewrite? The function of the parent class may not be required by the subclass, or you cannot use the shortcut key ALT + INSERT to select Override

polymorphism

That is, the same method can adopt many different behaviors depending on the sending object. The actual type of an object is determined, but there are many reference types that can point to an object

Conditions for the existence of polymorphism: there is an inheritance relationship, the subclass overrides the parent class method, and the parent class reference points to the subclass object

Note: polymorphism is the polymorphism of the method, and the property has no polymorphism

package oop.demo03;

public class Person {
    
    
    public void run(){
    
    
        System.out.println("run");
    }
}
package oop.demo03;

public class Student extends Person{
    
    
    public void run(){
    
    
        System.out.println("son");
    }
    public void eat(){
    
    
        System.out.println("eat");
    }
}
package oop.demo03;

public class Application {
    
    
    public static void main(String[] args) {
    
    
        // 一个对象的实际类型是不确定的
        // new Student(); new Person();的类型不确定
        // 一个对象的实际类型是确定的,但是指向它的引用类型就不确定了:父类的引用指向子类
        // Student 能调用的方法都是自己的或者继承父类的!
        Student s1 = new Student();
        // Person 属于是父类引用指向了子类,但是不能调用子类独有的方法
        Person s2 = new Student(); // 有继承关系的才行

        s1.run();
        s1.eat();
        s2.run();
        // 对象能执行哪些方法,主要看对象左边的类型,和右边关系不大
        ((Student) s2).eat(); // 子类重写了父类的方法,执行子类的方法必须强制转换
    }
}
// 输出界面如下
son
eat
son
eat

Process finished with exit code 0

Note on polymorphism:

  1. Polymorphism is the polymorphism of methods, but no polymorphism of properties
  2. The parent class and the subclass are polymorphic because they are related, otherwise it is a type conversion exception ClassCastException!
  3. Existing conditions: there is an inheritance relationship, and the method needs to be rewritten, and the parent class reference points to the subclass object Father f1 = new Son();

instanceof

instanceof judges what type an object is, and whether it has a parent-child relationship Object object = new Student();System.out.println(object instanceof Student);. Check the object object is a Student type, and return true.

type conversion

Mandatory type conversion can be from high to low parent class -> subclass; from low to high is automatically converted, similar to the relationship between float and int.

package oop.demo03;

public class Person {
    
    
    public void run(){
    
    
        System.out.println("run");
    }
}
package oop.demo03;

public class Student extends Person{
    
    
    public void go(){
    
    
        System.out.println("go");
    }
}
package oop.demo03;

public class Application {
    
    
    public static void main(String[] args) {
    
    
        // 高             低
        Person student = new Student();
        // student.go(); 此时 student 对象是 Person 类型,无法调用 Student 类的 go()方法
        // 需要将 Person类型转化为 Student 类型才能使用 Student 类的方法
        ((Student) student).go(); // 带括号强制转换
        // 低             高
        student.run(); // 可以直接使用 Person 类的方法
        
    }
}
// 输出界面如下
go

Process finished with exit code 0

Conversion summary: 1. The parent class reference points to the subclass object 2. Convert the subclass to the parent class and transform upward 3. Convert the parent class to the subclass and transform downward - forced conversion 4. Convenient method call and reduce code repetition of

Abstraction : encapsulation, inheritance, polymorphism

Polymorphic understanding reference https://www.cnblogs.com/chenssy/p/3372798.html

Encapsulation hides the internal implementation mechanism of the class, can change the internal structure of the class without affecting the use, and also protects the data. Its internal details are hidden from the outside world, and only its access methods are exposed to the outside world.

Inheritance is to reuse parent class code. If there is an IS-A relationship between two classes, inheritance can be used. At the same time, inheritance also paved the way for the realization of polymorphism. So what is polymorphism? What is the implementation mechanism of polymorphism? Please see me uncover them for you one by one:

The so-called polymorphism means that the specific type pointed to by the reference variable defined in the program and the method call issued through the reference variable are not , but are determined during the running of the program, that is, which reference variable will point to? For the instance object of the class, the method call issued by the reference variable is the method implemented in which class, which must be determined during the running of the program. Because the specific class is determined when the program is running, in this way, without modifying the source program code, the reference variable can be bound to various class implementations, which will cause the specific method called by the reference to change accordingly, that is, not modify The program code can change the specific code bound when the program is running, so that the program can choose multiple running states , which is polymorphism.

For example, you are a wine god and have a soft spot for wine. One day when I went home, I found that there were several glasses on the table filled with white wine. From the outside, it was impossible for us to know what kind of wine it was. Only after drinking could we guess what kind of wine it was. Once you drink it, it's Jiannanchun, then it's Wuliangye, and then it's Jiuguijiu... Here we can describe it as follows:

Wine a = Jiannanchun

Wine b = Wuliangye

Liquor c = alcoholic wine

What is shown here is polymorphism. Jiannanchun, Wuliangye, and Jiuguijiu are all subcategories of wine. We can refer to different subcategories only through the parent category of wine. This is polymorphism—we will only know the specific variable pointed to by the reference variable when it is running. instance object.

It is true that to understand polymorphism we must understand what "upward transformation" is. In the inheritance, we briefly introduced the upward transformation, and here is the wording: In the drinking example above, wine (Win) is the parent class, Jiannanchun (JNC), Wuliangye (WLY), and Jiuguijiu (JGJ) are the subclasses. We define the following code:

JNC a = new JNC();

For this code, it is very easy for us to understand that it is nothing more than instantiating an object of Jiannanchun! But what about this?

Wine a = new JNC();

Here we understand it this way, a Wine type a is defined here, which points to the JNC object instance. Since JNC is inherited from Wine, JNC can be automatically upgraded to Wine, so a can point to the JNC instance object. There is a very big advantage in doing this. In inheritance, we know that the subclass is an extension of the parent class, which can provide more powerful functions than the parent class. If we define a reference type of the parent class pointing to the subclass, then it will not only In addition to being able to refer to the commonality of the parent class, you can also use the powerful functions of the subclass.

But there are some shortcomings in the upward transformation, that is, it will inevitably lead to the loss of some methods and attributes, and we cannot obtain them. Therefore, the reference of the parent class type can call all the properties and methods defined in the parent class, and it can't catch up with the methods and properties that only exist in the subclass (it is overridden and the subclass is preferred).

public class Wine {
    
    
    public void fun1(){
    
    
        System.out.println("Wine 的Fun1...");
        fun2();
    }
    
    public void fun2(){
    
    
        System.out.println("Wine 的Fun2...");
    }
}

public class JNC extends Wine{
    
    
    /**
     * @desc 子类重载父类方法
     *        父类中不存在该方法,向上转型后,父类是不能引用该方法的
     * @param a
     * @return void
     */
    public void fun1(String a){
    
    
        System.out.println("JNC 的 Fun1...");
        fun2();
    }
    
    /**
     * 子类重写父类方法
     * 指向子类的父类引用调用fun2时,必定是调用该方法
     */
    public void fun2(){
    
    
        System.out.println("JNC 的Fun2...");
    }
}

public class Test {
    
    
    public static void main(String[] args) {
    
    
        Wine a = new JNC();
        a.fun1();
    }
}
-------------------------------------------------
Output:
WineFun.....
JNC 的Fun2...

From the running results of the program, we found that a.fun1() first runs fun1() in the parent class Wine, and then runs fun2() in the subclass JNC.

Analysis: In this program, the subclass JNC overloads the method fun1() of the parent class Wine, rewrites fun2(), and the overloaded fun1(String a) and fun1() are not the same method, because the method in the parent class Without this method, this method will be lost after upward transformation, so the Wine type reference that executes JNC cannot refer to the fun1(String a) method. And the subclass JNC rewrites fun2(), then the Wine reference pointing to JNC will call the fun2() method in JNC.

So for polymorphism we can summarize as follows:

The parent class reference pointing to the subclass can only access the methods and properties owned by the parent class due to the upward transformation , and for the methods that exist in the subclass but not in the parent class, the reference cannot be used, although it is heavy load the method. If the subclass overrides some methods in the parent class, these methods defined in the subclass must be used (dynamic connection, dynamic call) when calling these methods .

For object-oriented, polymorphism is divided into compile-time polymorphism and runtime polymorphism. Among them, polymorphism is static when editing, mainly referring to method overloading. It distinguishes different functions according to the parameter list. After editing, it will become two different functions. There is no polymorphism at runtime. . And runtime polymorphism is dynamic, it is realized through dynamic binding, which is what we call polymorphism.

polymorphic implementation

2.1 Realization conditions

At the beginning, it was mentioned that inheritance is preparing for the realization of polymorphism. The subclass Child inherits the parent class Father. We can write a parent class type reference pointing to the subclass. This reference can handle both the parent class Father object and the subclass Child object . When the same message is sent to the subclass or the parent class When an object is created, the object will perform different behaviors according to the reference to which it belongs, which is polymorphism. That is, polymorphism is the same message that makes different classes respond differently.

There are three necessary conditions for Java to achieve polymorphism: inheritance, rewriting, and upward transformation.

  • Inheritance: In polymorphism, there must be subclasses and parent classes that have an inheritance relationship.
  • Rewriting: The subclass redefines some methods in the parent class, and when these methods are called, the methods of the subclass are called.
  • Upward transformation: In polymorphism, it is necessary to assign the reference of the subclass to the parent class object, only in this way can the reference be able to call the method of the parent class and the method of the subclass.

​ Only when the above three conditions are met, can we use a unified logic implementation code to process different objects in the same inheritance structure, so as to achieve different behaviors. For Java, its polymorphic implementation mechanism follows a principle: when a superclass object reference variable refers to a subclass object, the type of the referenced object rather than the type of the reference variable determines whose member method to call , but this is called The method must be defined in the superclass, that is to say, the method is overridden by the subclass.

2.2 Realization form

There are two forms of polymorphism in Java. Inheritance and interfaces.

2.2.1. Polymorphism based on inheritance

The implementation mechanism based on inheritance is mainly manifested in the rewriting of some methods by the parent class and one or more subclasses inheriting the parent class, and the rewriting of the same method by multiple subclasses can show different behaviors.

public class Wine {
    
    
    private String name;
    
    public String getName() {
    
    
        return name;
    }

    public void setName(String name) {
    
    
        this.name = name;
    }

    public Wine(){
    
    
    }
    
    public String drink(){
    
    
        return "喝的是 " + getName();
    }
    
    /**
     * 重写toString()
     */
    public String toString(){
    
    
        return null;
    }
}

public class JNC extends Wine{
    
    
    public JNC(){
    
    
        setName("JNC");
    }
    
    /**
     * 重写父类方法,实现多态
     */
    public String drink(){
    
    
        return "喝的是 " + getName();
    }
    
    /**
     * 重写toString()
     */
    public String toString(){
    
    
        return "Wine : " + getName();
    }
}

public class JGJ extends Wine{
    
    
    public JGJ(){
    
    
        setName("JGJ");
    }
    
    /**
     * 重写父类方法,实现多态
     */
    public String drink(){
    
    
        return "喝的是 " + getName();
    }
    
    /**
     * 重写toString()
     */
    public String toString(){
    
    
        return "Wine : " + getName();
    }
}

public class Test {
    
    
    public static void main(String[] args) {
    
    
        //定义父类数组
        Wine[] wines = new Wine[2];
        //定义两个子类
        JNC jnc = new JNC();
        JGJ jgj = new JGJ();
        
        //父类引用子类对象
        wines[0] = jnc;
        wines[1] = jgj;
        
        for(int i = 0 ; i < 2 ; i++){
    
    
            System.out.println(wines[i].toString() + "--" + wines[i].drink());
        }
        System.out.println("-------------------------------");

    }
}
OUTPUT:
Wine : JNC--喝的是 JNC
Wine : JGJ--喝的是 JGJ
-------------------------------

In the above code, JNC and JGJ inherit Wine and rewrite the drink() and toString() methods. The result of program operation is to call the method in the subclass and output the names of JNC and JGJ. This is the performance of polymorphism. Different objects can perform the same behavior, but they all need to implement it through their own implementation, which benefits from upward transformation. We all know that all classes inherit from the superclass Object, and the toString() method is also a method in Object. When we write like this:

Object o = new JGJ();

      System.out.println(o.toString());

The output is Wine : JGJ.

The inheritance chain relationship among Object, Wine, and JGJ is: JGJ—>Wine—>Object. So we can say this: When a subclass overrides a method of the parent class is called, only the method at the end of the object inheritance chain will be called . But notice if you write like this:

Object o = new Wine();

System.out.println(o.toString());

The output should be Null, because JGJ does not exist in the inheritance chain of this object. Therefore, polymorphism based on inheritance can be summarized as follows: For a parent class type that references a subclass, when processing the reference, it is applicable to all subclasses that inherit the parent class. Different, the behavior produced by performing the same action is also different. If the parent class is an abstract class, then the subclass must implement all the abstract methods in the parent class, so that all subclasses of the parent class must have a unified external interface, but their internal specific implementations can be different. In this way, we can use the uniform interface provided by the top-level class to handle the methods of this level.

2.2.2. Polymorphism based on interface implementation

Inheritance is manifested by several different subclasses that override the same method of the parent class, then it can be manifested by several different classes that implement the interface and override the same method in the interface. In the polymorphism of the interface, the reference to the interface must be an instance program that specifies a class that implements the interface. At runtime, the corresponding method is executed according to the actual type of the object reference.

Inheritance is single inheritance, which can only provide a consistent service interface for a group of related classes. But the interface can be multi-inherited and multi-implemented. It can use a group of related or unrelated interfaces to combine and expand, and can provide a consistent service interface to the outside world. So it has better flexibility than inheritance.

Detailed explanation of the static keyword

package oop.demo01;

import oop.demo03.Person;

public class Student {
    
    
    // 静态属性
    private static int age; // 静态变量
    private double score; // 普通变量

    // 静态方法
    // 在同一个类中,普通方法可以调用静态方法,反之则不行,这是加载顺序决定的
    public void run(){
    
    
        System.out.println("run");
        go();
    }

    public static void go(){
    
    
        System.out.println("go");
    }

    public static void main(String[] args) {
    
    
        Student student = new Student();
        System.out.println(student.score); // 普通变量只能通过实例访问
        System.out.println(student.age);

        System.out.println(Student.age); // 静态变量可以通过类访问
    }
}

Detailed code block

package oop.demo01;

public class Person {
    
    
    {
    
    
        // 匿名代码块,第二个执行,可以赋一些初始值
        System.out.println("匿名代码块");
    }
    static{
    
    
        // 静态代码块,第一个执行,但只执行一次
        System.out.println("静态代码块");
    }

    public Person() {
    
    
        System.out.println("构造器");
    }

    public static void main(String[] args) {
    
    
        Person person = new Person(); // 第三个执行
		System.out.println("====================");
        Person person2 = new Person();
    }
}
// 输出界面如下
静态代码块
匿名代码块
构造器
====================
匿名代码块
构造器

Process finished with exit code 0
package oop.demo01;
// 静态导入包,就不用每次都写全称 Math.random() 可以直接写 random()
import static java.lang.Math.random;
public class Test {
    
    

    public static void main(String[] args) {
    
    
        System.out.println(random());
    }
}

Note: final classes are constants and cannot be inherited

5. Abstract classes and interfaces

The abstract modifier can be used to modify methods or classes. If a method is modified, the method is an abstract method; if a class is modified, the class is an abstract class. There may be no abstract methods in an abstract class, but the class with abstract methods must be declared as an abstract class.

An abstract class cannot use the new keyword to create an object, it is used to allow subclasses to inherit. Abstract method, only method declaration, no method implementation, it is used to allow subclasses to achieve. If the subclass inherits the abstract class, the abstract method that the abstract class does not implement must be implemented for a long time, otherwise the subclass must also be declared as an abstract class

package oop.demo02;

// 抽象类;子类 extends 只能单继承,只有接口可以多继承
public abstract class Action {
    
    

    // 只是一个声明,没有方法体;一种约束,子类帮忙实现
    public abstract void doSomething();
    // 1.不能new这个抽象类,只能考子类去实现它
    // 2.抽象类中可以写普通方法
    // 3.抽象方法必须在抽象类中
    // 优点:抽象出来,提高开发效率
}
package oop.demo02;

// 抽象类的所有方法,继承了它的子类,都必须要实现它的方法;除非它也是抽象类
public class A extends Action{
    
    
    @Override
    public void doSomething() {
    
    

    }
}

interface

  • Ordinary class: only concrete implementation
  • Abstract class: both concrete implementation and specification (abstract method)!
  • Interfaces: only specifications! I can't write the method by myself~professional constraints! Separation of Constraints and Implementation: Interface-Oriented Programming

An interface is a specification, a defined set of rules that embodies the idea of ​​"if you are... you must be able to..." in the real world. If you are an angel, you must be able to fly. If you are a car, you have to run. The essence of an interface is a contract , just like the law between us, everyone abides by it after it is formulated. The essence of OO is the abstraction of objects, and the best embodiment of this is the interface. Why we discuss design patterns only for languages ​​​​with abstraction capabilities (such as C++, Java, etc.), because the research of design patterns is actually how to abstract reasonably.

The keyword for declaring a class is class and the keyword for declaring an interface is interface

package oop.demo05;

// 接口定义需要的是抽象思维——Java架构师
// interface 关键字定义接口,接口都需要有实现类
public interface UserService {
    
    
    // 接口中定义的所有属性都是常量 public final
    int AGE = 20;
    // 接口中定义的所有方法都是默认抽象的 public static
    void add(String name);
    void delete(String name);
    void update(String name);
    void query(String name);
}
package oop.demo05;

public interface TimeService {
    
    
    void timer();
}
package oop.demo05;

// 实现类通过关键字 implements 对接口类实现
// 实现了接口的类,就需要重写接口中规范的方法
// 利用接口实现了多继承
public class UserServiceImpl implements UserService,TimeService{
    
    
    @Override
    public void add(String name) {
    
    

    }

    @Override
    public void delete(String name) {
    
    

    }

    @Override
    public void update(String name) {
    
    

    }

    @Override
    public void query(String name) {
    
    

    }

    @Override
    public void timer() {
    
    

    }
}

Interface summary: The interface is 1. Constraints 2. Define some methods for different people to implement 3. The methods in the interface have the keyword public abstract by default 4. The properties in the interface have the keyword public static final by default 5. The interface cannot be instantiated, There is no construction method in the interface 6. implements can implement multiple interfaces 7. The implementation class must rewrite the methods in the interface

6. Inner classes

An inner class is to define a class inside a class. For example, if a class B is defined in class A, then class B is called an inner class relative to class A, and class A is an outer class relative to class B. The inner class can directly access some things of the outer class, such as private properties, which cannot be done by normal classes.

package oop.demo06;
// 外部类
public class Outer {
    
    

    private int ID = 10;
    public void out(){
    
    
        System.out.println("这是外部类的方法");
    }

    public class Inner{
    
    
        public void in(){
    
    
            System.out.println("这是内部类的方法");
        }
        // 可以获得外部类的私有属性
        public void getID(){
    
    
            System.out.println(ID);
        }
    }
}
package oop.demo06;

public class Application {
    
    
    public static void main(String[] args) {
    
    
        Outer outer = new Outer();
        // 通过外部类来实例化内部类
        Outer.Inner inner = outer.new Inner();
        inner.getID();
    }
}
// 输出界面如下
10

Process finished with exit code 0
package oop.demo06;
// 外部类
public class Outer {
    
    
    
}

//一个Java类文件中可以有多个class,但是只能有一个public class
//这样就可以在一个文件内测试了
class A{
    
    
    public static void main(String[] args) {
    
    
        
    }
}

exception mechanism

1. What is an exception

  • In actual work, the situation encountered cannot be perfect. For example: in a certain module you write, the user input may not meet your requirements. Your program needs to open a certain file. This file may not exist or the file format is wrong. If you want to read the data from the database, the resulting data may be empty. Yes, our program is running again, the memory or the hard disk may be full, and so on.
  • During the running of a software program, it is very likely to encounter the abnormal problems just mentioned. We call them abnormal, and the English is: Exception, which means exception. These, exceptions, or exceptions, how can the programs we write make reasonable handling without causing the program to crash.
  • Abnormalities refer to various unexpected situations that occur during program operation. Abnormalities occur during program operation and affect the normal program execution flow.

To understand how Java exception handling works, you need to understand the following three types of exceptions:

  1. Checked Exceptions: The most representative checked exceptions are those caused by user errors or problems, which cannot be foreseen by the programmer. For example, an exception occurs when trying to open a file that does not exist, and these exceptions cannot be simply ignored at compile time.
  2. Runtime exceptions: Runtime exceptions are exceptions that may be avoided by the programmer. In contrast to checked exceptions, runtime exceptions can be ignored at compile time.
  3. Error ERROR: An error is not an exception, but a problem that is out of the programmer's control. Errors are usually ignored in code. For example, when the stack overflows, an error occurs, and they are not checked at compile time.

Java Exception Handling Framework

Java handles exceptions as objects and defines a base class java.lang.Throwable as the superclass of all exceptions. Many exception classes have been defined in the Java API, which are divided into two categories, Error and Exception.

insert image description here

2. Exception architecture

Error

  • Error class objects are generated and thrown by the Java Virtual Machine, and most errors have nothing to do with actions performed by the code writer.
  • Java virtual machine operation error (Virtual MachineError), when the JVM no longer has the memory resources needed to continue the operation, OutOfMemoryError will appear. When these exceptions occur, the Java Virtual Machine (JVM) generally chooses the thread to terminate;
  • It also occurs when the virtual machine tries to execute the application, such as class definition error (NoClassDefFoundError), link error (LinkageError). These errors are untraceable because they are outside the control and processing capabilities of the application program, and most of them are conditions that are not allowed to occur when the program is running.

Exception

  • There is an important subclass RuntimeException in the Exception branch (runtime exception)

    ArrayIndexOutOfBoundException (array subscript out of bounds)

    NullPointerException (null pointer exception)

    ArithmeticException (arithmetic exception)

    MissingResourceException (missing resource)

    ClassNotFoundException (cannot find class) and other exceptions, these exceptions are unchecked exceptions, you can choose to catch and process them in the program, or you can not handle them

  • These exceptions are generally caused by program logic errors, and the program should avoid such exceptions as much as possible from a logical point of view;

  • The difference between Error and Exception: Error is usually a catastrophic fatal error that cannot be controlled and handled by the program. When these exceptions occur, the Java Virtual Machine (JVM) generally chooses to terminate the thread; Exception is usually a program that can be Handled, and these exceptions should be handled as much as possible in the program.

3. Java exception handling mechanism

throw exception; catch exception

Five keywords for exception handling: try, catch, finally, throw, throws

package exception;

public class demo01 {
    
    
    public static void main(String[] args) {
    
    
        int a = 1;
        int b = 0;

        // 类似 if else 结构如果 try 代码块内发生 catch() 内的异常就执行 catch 代码块
        try{
    
    // try 代码块必须;把可能有异常的代码放进去进行监控
            System.out.println(a/b);
        }catch (ArithmeticException e){
    
    // catch 代码块必须;针对可能的异常进行处理()里是想要捕获的类型
            System.out.println("程序出现异常,变量b不能为0");
        }finally {
    
    // finally 代码块非必须;处理善后工作如资源归还关闭服务等,不论有没有出现异常都会执行
            System.out.println("finally");
        }
    }

}
// 输出界面如下
程序出现异常,变量b不能为0
finally

Process finished with exit code 0
package exception;

public class demo01 {
    
    
    public static void main(String[] args) {
    
    
        int a = 1;
        int b = 0;
		// 选中代码 CRTL + ALT + T 可以快捷键编写try catch代码
        // 捕获结构类似 if else 结构可以叠加,从上至下范围越来越大
        try{
    
    
            System.out.println(a/b);
        }catch (Error e){
    
    
            System.out.println("Error");
        }catch(Exception e){
    
    
            System.out.println("Exception");
        }catch(Throwable t){
    
    
            System.out.println("Throwable");
        }
        finally {
    
    
            System.out.println("finally");
        }
    }

}
// 输出界面如下
Exception
finally

Process finished with exit code 0
package exception;

public class demo01 {
    
    
    public static void main(String[] args) {
    
    
        new demo01().test(1,0); // 哪怕方法中没有定义除法运算也会抛出异常
    }

    // 假设这个方法中,处理不了这个异常,方法上抛出异常
    public void test(int a, int b){
    
    
        if( b == 0){
    
     // throw 与 throws 不同
            throw new ArithmeticException(); // 主动抛出异常,一般在方法中使用
        }
    }
}
// 输出界面如下
Exception in thread "main" java.lang.ArithmeticException
	at exception.Test.test(demo01.java:10)
	at exception.Test.main(demo01.java:5)

Process finished with exit code 1

4. Custom exceptions

Using Java's built-in exception classes can describe most of the exceptions that occur during programming. Before that, users can also customize exceptions. User-defined exception classes only need to inherit the Exception class.

Using a custom exception class in a program can be roughly divided into the following steps:

  1. Create a custom exception class
  2. Throw an exception object through the throw keyword in the method
  3. If the exception is handled in the method that currently throws the exception, you can use the try-catch statement to catch and handle it; otherwise, use the throws keyword to indicate the exception to be thrown to the method call at the declaration of the method, and continue to the next step
  4. Catch and handle the exception in the caller of the exception method
package exception;

// 自定义的异常类
public class MyException extends Exception{
    
    

    // 传递数字 > 10;
    private int detail;

    public MyException(int a){
    
    
        this.detail = a;
    }
    // toString:异常的打印信息

    @Override
    public String toString() {
    
    
        return "MyException{" +
                "detail=" + detail +
                '}';
    }
}
package exception;

public class Test {
    
    

    // 可能会存在异常的方法
    static void test(int a) throws MyException {
    
    
        System.out.println("传递的参数为:" + a);

        if( a > 10){
    
    
            throw new MyException(a); // 主动抛出异常,一般在方法中使用
        }
        System.out.println("OK");
    }

    public static void main(String[] args) {
    
    
        try {
    
     // 捕获异常
            test(11);
        } catch (MyException e) {
    
    
            System.out.println("MyException:" + e);;
        }
    }
}
// 输出界面如下
传递的参数为:11
MyException:MyException{
    
    detail=11}

Process finished with exit code 0

5. Summary in practical application

  • When handling runtime exceptions, use logic to reasonably avoid and assist try-catch processing
  • After multiple catch blocks, you can add a catch (Exception) to handle exceptions that may be missed
  • For uncertain code, try-catch can also be added to handle potential exceptions
  • Try to deal with it, remember to simply call printStackTrace() to print the output
  • How to handle exceptions depends on different business requirements and exception types.
  • Try to add a finally statement block to release the occupied resources

Guess you like

Origin blog.csdn.net/m0_47455189/article/details/120629412