Java learning notes

Java learning notes

1. Environmental construction

Install JDK

Because Java programs must run on the JVM, the first thing is to install the JDK.

Search JDK 13 to make sure that Oracle's official website Download the latest stable JDK:

Setting environment variables

After installing JDK, you need to set up a Java_ The environment variable of home, which points to the installation directory of JDK. Under Windows, it is the installation directory, similar to:

C:\Program Files\Java\jdk-13

Under Mac, it's in ~ /. Bash_ In the profile, it is:

export JAVA_HOME=`/usr/libexec/java_home -v 13`

Then, put Java_ The bin directory of home is attached to the system environment variable PATH. Under Windows, it looks like this:

Path=%JAVA_HOME%\bin;<Other existing paths>

Under Mac, it's in ~ /. Bash_ In the profile, it looks like this

export PATH=$JAVA_HOME/bin:$PATH

Put java_ The bin directory of home is added to PATH so that java can be run in any folder. Open the command prompt window and enter the command java -version. If everything is normal, you will see the following output:

┌────────────────────────────────────────────────────────┐
│Command Prompt                                    - □ x │
├────────────────────────────────────────────────────────┤
│Microsoft Windows [Version 10.0.0]                      │
│(c) 2015 Microsoft Corporation. All rights reserved.    │
│                                                        │
│C:\> java -version                                      │
│java version "13" ...                                   │
│Java(TM) SE Runtime Environment                         │
│Java HotSpot(TM) 64-Bit Server VM                       │
│                                                        │
│C:\>                                                    │
│                                                        │
│                                                        │
└────────────────────────────────────────────────────────┘

If the version number you see is not 13 but 12 or 1.8, it indicates that there are multiple jdks in the system, and the default JDK is not JDK 13. You need to mention JDK 13 in front of PATH.

If you get an error output:

┌────────────────────────────────────────────────────────┐
│Command Prompt                                    - □ x │
├────────────────────────────────────────────────────────┤
│Microsoft Windows [Version 10.0.0]                      │
│(c) 2015 Microsoft Corporation. All rights reserved.    │
│                                                        │
│C:\> java -version                                      │
│'java' is not recognized as an internal or external comm│
│and, operable program or batch file.                    │
│                                                        │
│C:\>                                                    │
│                                                        │
│                                                        │
│                                                        │
└────────────────────────────────────────────────────────┘

2.Java basic syntax

This paper briefly introduces the concepts of class, object, method and instance.

  • Object: an object is an instance of a class. There is an object and an object. Its are: color, name and method; Behaviors include wagging tail, barking, eating, etc.
  • Class: a class is a template that describes the behavior and state of an object.
  • Methods: methods are behaviors. A class can have many methods. Logical operation, data modification and all action methods are completed in.
  • Instance variables: each variable object has a unique instance, and the state of the object is determined by the values of these instance variables.

First program HelloWorld

/**
 * Comments that can be used to automatically create documents
 */
public class Hello {
    public static void main(String[] args) {
        // Output text to screen:
        System.out.println("Hello, world!");
        /* Multiline comment start
        Note Content 
        End of comment */
    }
} // End of class definition

Variables and data types

Divided by data type: variables of basic type and variables of reference type.

It is divided by the declared location: local variables (variables defined inside the method or statement block) and member variables (variables defined outside the method and inside the class)

Basic type variables

In Java, variables must be defined before use. When defining variables, you can give them an initial value. For example:

int x = 1;

Basic data type

The basic data type is the type that the CPU can perform operations directly. Java defines the following basic data types:

  • Integer type: byte, short, int, long
  • Float type: float, double
  • Character type: char
  • boolean type: boolean

Basic data type conversion:

  • Types with small capacity are automatically converted to types with large capacity
  • Byte, short and int, which will be converted to int type when recalculated
  • If you convert an int value to a float value or a long value to a double value, you do not need to cast, but you may lose precision

Cast type:

  • When converting a type with large capacity to a data type with small capacity, a cast character shall be added

Methods and arrays

Definition of method:

A method (also known as a function) is a block of code for a specific function. Methods to improve the reusability and readability of the program.

Format of method

// Syntax:
// Access permission modifier [other modifiers such as static] return value type method name (parameter type 1, parameter 1, parameter type 2, parameter 2,...) {/ / parameter list
	// Method body
	 	return Return value;
}

Parameters:

Actual parameters: the parameters that actually participate in the operation.

Formal parameter: it is defined in the method and used to accept actual parameters;

Parameter type: the data type of the parameter

Parameter name: variable name

Method language sentence: it is the code that completes the function

be careful:

1. If the formal parameter is not used in the current method, the formal parameter list can be empty

2. The types of argument and formal parameter should be compatible with each other, and the value range of argument should be less than or equal to the value range of formal parameter type

In the calling method, if the method we define has parameters, we must pass in this value while calling the method, that is, assign a value to the parameters in the current method, and this passed in value is called an actual parameter, that is, an actual parameter

Argument: parameter value passed in

Formal parameter: accept the value passed from the argument

Note: the actual parameter name and formal parameter name can be the same or different

Summary: a formal parameter is a variable, an actual parameter is a value, and parameter transfer is to assign a value to a formal parameter

Method

return: end method

return value: This is the result of Gong en, which is returned to the caller.

be careful:

  1. If the current method does not have a return value type, that is, the return value type is void, return may not be written in the current method
  2. Return means to end a method. You can also return the return value to the caller calling the current method
  3. Return when returning a value, you can only return one value at a time. You can't return multiple values
  4. There can be multiple return s in a method, but only one can be executed, so you need to judge

practice:

  1. Judge whether any given year is a leap year

    public class test {
        public static void main(String[] args){
            boolean bool = isRunNian(2017);
            if(bool){
                System.out.println("It's a leap year");
            }else{
                System.out.println("It's a normal year");
            }
        }
        public static boolean isRunNian(int year){
            if((year%4==0 && year%100!=0) || year%400==0){
                return true;
            }else{
                return false;
            }
        }
    }
    
  2. Prints right triangles based on the number of parameters passed in

    public class printTriangle {
        public static void main (String[] args){
            Scanner input = new Scanner(System.in);
            int num = input.nextInt();
            print(num);
        }
        public static void print(int line) {
            for(int i=1 ; i<=line ; i++) { // Number of control rows
                for(int j=i;j<line;j++) { 
                    System.out.print(" ");
                }
                for(int k=1; k<=i*2-1; k++) {
                    System.out.print("*");
                }
                System.out.println();
            }
        }
    }
    

Method overload

Method overloading: overloading method

You can create multiple methods in a class, which have the same name, but different parameters and different definitions;

The return value cannot be used as an overloaded condition

// For example:
	public void method(int a){...}
	public void method(char b){...}

Definition of array

Array: a collection of variables that can store values of the same data type

When a group of data of the same type needs to be stored, if a single variable is used for storage, we will define several variable names, which will be very cumbersome and not conducive to maintenance

Array assignment method

Four types:

  • Initialize each array in the array with the default initial value

    Syntax: array element type [] array name = new array element type [number of elements in array (length of array)]

    For example: int [] scores = new int[3];

  • Declare first, and then give the default initial value

    Syntax: array element type [] array name;

    Array name = new array element type [number of elements in the array (length of the array)];

    For example: int [] scores;

    scores = new int[3];

  • Declare first, and then initialize with a specific value

    Syntax: array element type [] array name = new array element type [] {element 1, element 2,...};

    For example: int [] scores = new int[]{56, 78, 98};

  • The third method can be simplified as (assigning an array with an array constant value)

    Syntax: array type [] array name = {element 1, element 2,...};

    For example: int [] scores = {56, 78, 98}

Traversal of array

Traversal: say each element in the array in turn

Access the elements of the array by subscript

Subscript: from 0 to array length - 1

  • Traversal method 1: ordinary for loop

    Syntax: for (int i = 0; I < length of array; I + +){

    / / i: cyclic variable, which is also the subscript of the array (value range [0, length of the array])

    Type variable of element in array = array name [i];

    }

  • Traversal mode 2: use enhanced for loop [foreach loop]

    Syntax: for (type of element in array variable: array name){

    Type of element in the array: temporary variable = variable;

    }

Array example

  1. Guessing game, input any data from the keyboard to judge whether the number series contains this number

    public class test2 {
        // Guessing game, input any data from the keyboard to judge whether the number series contains this number
        public static void  main(String[] args) {
            int[] nums = {2,32,23,54,60};
            Scanner input = new Scanner(System.in);
            System.out.println("Please enter the number you want to guess: (within 60)");
            int userNum = input.nextInt();
            boolean flag = false;
            for(int i:nums){
                if(userNum == i){
                    flag = true;
                    break;
                }
            }
            if(flag) {
                System.out.println("Congratulations, you guessed right");
            }else{
                System.out.println("Guess wrong. Keep trying");
            }
        }
    }
    
    
  2. Print regular triangles

Multidimensional array example:

1. Join the loser programmer competition. There are three classes with three students in each class. Record the results of each student and calculate the average score of each class.

public class test3 {
    public static void main(String[] args){
        int [][] scores = {{99,78,50},{90,86},{67,87,56}};
        int classLen = scores.length;
        for(int[] i:scores){
            int sum = 0;
            for(int j:i){
                sum += j;
            }
            int avg = sum / i.length;
            System.out.println("Average score:"+avg);
        }
    }
}

Maximum minimum algorithm

Algorithm for finding maximum and minimum values

Maximum: find the maximum number in a sequence

public class test4 {
    public static void main(String[] args){
        int[] nums = {1,2,3,4,5,6};
        int max = max(nums);
        System.out.println(max);
    }
    public static int max(int [] nums){
        int max = nums[0];
        int len = nums.length;
        for(int i = 1;i<len;i++){
            if(max < nums[i]){
                nums[i] = nums[i] + max;
                max = nums[i] - max;
                nums[i] = nums[i] - max;
            }
        }
        return max;
    }
}

Minimum: find the smallest number in a sequence

public class test4 {
    public static void main(String[] args){
        int[] nums = {1,2,3,4,5,6};
        int min = min(nums);
        System.out.println(min);
    }
    public static int max(int [] nums){
        int min = nums[0];
        int len = nums.length;
        for(int i = 1;i<len;i++){
            if(min > nums[i]){
                nums[i] = nums[i] + min;
                min = nums[i] - max;
                nums[i] = nums[i] - min;
            }
        }
        return min;
    }
}

Bubble sort algorithm

Bubble sort algorithm

The operation of bubble sorting algorithm is as follows: (from back to front)

Compare adjacent elements. If the first is larger than the second, swap them.

Do the same for each pair of adjacent elements, from the first pair at the beginning to the last pair at the end. At this point, the last element should be the largest number.

Repeat the above steps for all elements except the last one.

Continue to repeat the above steps for fewer and fewer elements each time, knowing that no pair of numbers need to be compared.

The sequence of the same elements has not changed, so bubble sorting is a stable sorting algorithm

public class test5 {
    public static void main(String[] args){
        int[] nums = {10,21,3,34,5,19};
        int len = nums.length-1;
        for(int i = 0; i < len;i++){
            for(int j = 0; j < len-i;j++){
                if(nums[j] > nums[j+1]){
                    nums[j+1] = nums[j]+nums[j+1];
                    nums[j] = nums[j+1] - nums[j];
                    nums[j+1] = nums[j+1] - nums[j];
                }
            }
        }
        for(int n:nums){
            System.out.println(n);
        }
    }
}

Select Sorting Algorithm

Each time, the smallest (or largest) element is selected from the data elements to be sorted, and the order is placed at the end of the ordered sequence until all the data elements to be sorted are finished. Selective sorting is an unstable sorting method

public class test6 {
    public static void main(String[] args){
        int[] nums = {10,21,3,34,5,19};
        int len = nums.length;
        int minIndex;
        for(int i=0;i<len;i++){
            minIndex = i;
            for(int j=i+1;j<len-1;j++){
                if(nums[minIndex] > nums[j]){
                    minIndex = j;
                }
            }
            if(minIndex != i){
                if(nums[i] > nums[minIndex]){
                    nums[minIndex] = nums[i]+nums[minIndex];
                    nums[i] = nums[minIndex] - nums[i];
                    nums[minIndex] = nums[minIndex] - nums[i];
                }
            }
        }
        for(int n:nums){
            System.out.println(n);
        }
    }
}

Direct insertion sorting algorithm

Direct insertion sorting algorithm

(insert after finding the proper position from back to front)

**Basic idea: * * at each step, insert a record to be sorted into the appropriate position of the previously ordered subsequence according to its sequence code size (after finding the appropriate position from back to front) until all records are inserted and sorted.

public class test7 {
    public static void main(String[] args){
        int[] nums = {10,21,3,34,5,19};
        for(int i = 1;i<nums.length;i++){
            int temp = nums[i];
            int j;
            for(j = i-1;j>=0;j--){
                if(nums[j] > temp){
                    nums[j+1] = nums[j];
                }else{
                    break;
                }
            }
            if(temp != nums[j+1]){
                nums[j+1] = temp;
            }
        }
        for(int n:nums){
            System.out.println(n);
        }
    }
}

Binary search algorithm

Dichotomy search (half search): the premise is to compare the elements to be searched with the elements corresponding to the intermediate index value in the ordered array. If it is greater than the elements corresponding to the intermediate index value, go to the right half for search, otherwise go to the left half for search. And so on. Until it is found, a negative number will be returned if it is not found.

public class test8 {
    public static void main(String[] args){
        int[] nums = {1,2,3,4,5,6};
        int index = binarySearch(nums,3);
        System.out.println(index);
    }
    public static int binarySearch(int[] nums, int key){
        int start = 0;
        int end = nums.length-1;
        while (start<=end){
            int middle = (start+end)/2;
            if(nums[middle]>key){
                end = middle-1;
            }else if(nums[middle]<key){
                start = middle+1;
            }else{
                return middle;
            }
        }
        return -1;
    }
}

Arrays class

Arrays utility class: various methods used to manipulate arrays, such as sorting and searching

Common methods:

  • Find using dichotomy

    Arrays.binarySearch(int [] array,int value);

  • The contents of the array are output in the form of a string

    Arrays.toString(int [] array);

  • Array sorting

    Arrays.sort(int[] array);

  • Copies the specified array

    Arrays.copyOf(int[] array,int length)

    Arrays.copyOf(int[] array,int form,int to)

    System.arraycopy(Object src, int s rcPos,Object dest,int destPos,int length)

  • Determine whether two arrays are equal

    Arrays.equels();

  • Fills the array with the specified elements

    Arrays.fill()

Comprehensive case of two-color ball simulation

1, Two color ball lottery playing method

Play instructions:

The two-color betting is divided into red number area and blue ball number area. The red ball number range is 0133 and the blue ball number range is 0116. The two-color ball sets out 6 numbers from 33 red balls and 1 number from 16 blue balls as the lieutenant general number in each period. The playing method of the two-color ball is to guess the 6 red ball numbers and 1 blue ball number of the lottery number in unlimited order

2, Case analysis

1. How to produce blue ball and red ball?

2. How to accept user selection?

3. How to verify whether winning?

4. Publish the number of this issue?

3, Implementation steps:

1. Overall realization idea

2. Random value non repetition algorithm (system and user)

3. The logic of judging whether to win the prize

4. Result output

import java.util.Arrays;
import java.util.Random;
import java.util.Scanner;
public class test9 {
    public static void main(String[] args){
        // Define related variables
        int[] userRedBall = new int[6];// Red ball number selected by the user
        int[] sysRedBall = new int[6];// System generated red ball number
        int userBlueBall = 0;// User selected basketball number
        int sysBlueBall = 0;// System generated basketball number
        int redCount = 0;// Record the correct red ball selected by the user
        int blueCount = 0;// Record the correct basketball selected by the user
        int [] redBall = new int[33]; //Red ball number for storing 1-33
        for(int i = 0;i<redBall.length;i++){
            redBall[i] = i+1;
        }
        // Game start prompt
        System.out.println("The two-color ball game begins, good luck");
        System.out.println("Do you want machine selection or manual selection: (1: machine selection, 2: preferred)");
        Scanner input = new Scanner(System.in);
        Random r = new Random();
        boolean flag = true;
        while(flag){
            int isAuto = input.nextInt();
            switch (isAuto){
                case 1:
                // Machine selection
                    computerSelect(redBall,userRedBall);
                    userBlueBall = r.nextInt(16)+1;
                    flag = false;
                    break;
                case 2:
                // Hand selection
                    System.out.println("Please select 6 red ball numbers (1)-33)");
                    for(int i=0;i<userRedBall.length;i++){
                        userRedBall[i] = input.nextInt();
                    }
                    System.out.println("Please select a basketball number (1)-16)");
                    userBlueBall = input.nextInt();
                    flag = false;
                    break;
                default:
                    System.out.println("Do you want machine selection or manual selection: (1: machine selection, 2: preferred)");
                    break;
            }
        }
        // System randomly generated number
        computerSelect(redBall,sysRedBall);
        sysBlueBall = r.nextInt(16)+1;
        for(int i=0;i<userRedBall.length;i++){
            for(int j=0;j<sysRedBall.length-redCount;j++){
                if(userRedBall[i] == sysRedBall[j]){
                    int temp = userRedBall[i];
                    userRedBall[i] = sysRedBall[userRedBall.length-1-redCount];
                    sysRedBall[userRedBall.length-1-redCount] = temp;
                    redCount++;
                    break;
                }
            }
        }
        if(userBlueBall == sysBlueBall){
            blueCount = 1;
        }
        if(blueCount==0 && redCount<=3){
            System.out.println("Didn't win the prize");
        }else if(blueCount==1 && redCount<3){
            System.out.println("Six grades, five dollars");
        }else if(blueCount==1 && redCount==3 || blueCount==0 && redCount==4){
            System.out.println("Five grades, 10 yuan");
        }else if(blueCount==1 && redCount==4 || blueCount==0 && redCount==5){
            System.out.println("I won the fourth grade, 200 yuan");
        }else if(blueCount==1 && redCount==5){
            System.out.println("Three grades, 3000 yuan");
        }else if(blueCount==0 && redCount==6){
            System.out.println("Three grades, 150 w Dollars");
        }else if(blueCount==1 && redCount==6){
            System.out.println("Three grades, 500 w Dollars");
        }else{
            System.out.println("System error, winning invalid");
        }
        // System number
        System.out.println("The red ball of this issue");
        Arrays.sort(sysRedBall);
        System.out.println(Arrays.toString(sysRedBall));
        System.out.println("The winning basketball in this issue");
        System.out.println(sysBlueBall);
        // User number
        System.out.println("The red ball of your choice");
        Arrays.sort(userRedBall);
        System.out.println(Arrays.toString(userRedBall));
        System.out.println("The basketball you choose");
        System.out.println(userBlueBall);
    }
    public static void computerSelect(int[] redBall,int[] userRedBall){
        Random r = new Random();
        int index = -1;
        for(int i=0;i<userRedBall.length;i++){
            index = r.nextInt(redBall.length-i);
            userRedBall[i] = redBall[index];
            //change of position
            int temp = redBall[index];
            redBall[index] = redBall[redBall.length-1-i];
            redBall[redBall.length-1-i] = temp;
        }
    }
}

3. Basic concepts of object-oriented

1, What is object-oriented

1. Object oriented is a programming idea.

2. Object oriented is a way of thinking.

2, Resume object-oriented thinking mode:

1. First overall, then local

2. Abstract first, then concrete

3. What can be done and how

3, How to learn object oriented

1. Master the syntax of an object-oriented language

2. Be familiar with object-oriented design principles

3. Be familiar with object-oriented design pattern

Classes and objects

  1. Category: classification and category
  2. Through classification, we can distinguish different kinds of things, which we often do in our daily life.
  3. Therefore, a class is a set of things with the same characteristics (attributes) and behaviors (Methods).

Relationship between class and object

  1. Class is a product of commonness and a comprehensive feature, while object is a product of individuality and an individual feature.

  2. Class consists of properties and methods

    Attribute: it is equivalent to the characteristics of one by one

    Method: it is equivalent to people's behavior one by one, such as talking, eating, singing and sleeping

Definition format of classes and objects

In Java, you can use the following statements to define a class:

class name{

Attribute name;

Return value type method name () {}

}

Definition of object:

If a class wants to operate, it must rely on the object. The definition format of the object is as follows:

Class name object name = new class name ();

Objects can be generated according to the above format.

If you want to access properties or methods in a class (definition of methods)

You can rely on the following grammatical forms:

To access properties in a class:

Object. Attribute;

To call a method in a class:

Object. Method ();

Memory analysis of objects

  1. The new keyword means to create an object
  2. The new keyword represents an instantiated object
  3. The new keyword indicates the requested memory space

Note: if an object does not apply for memory space, a null pointer exception will be reported

Class and object summary

  • new keyword: it means to apply for space from memory. It also means to instantiate an object and create an object.
  • The size of an object in memory, the sum of the memory size occupied by all the attributes of the object. Reference type variables occupy 4 bytes on 32-bit systems and 8 bytes on 64 bit systems. Plus the size of the hidden data of the crooked object.
  • The same type can be assigned
  • Different references point to the same object. If any reference changes the value of the object, other references will be reflected.
  • When programming, you should pay attention to releasing the object as soon as possible when you decide not to use the object: reference = null
  • When an object in the push is not pointed to by any reference variable, the object will be considered as a garbage object by the GC program of the JVM and will be recycled

Encapsulation

1, Encapsulation concept

  1. Encapsulation is one of the three characteristics of object-oriented thought.

  2. Encapsulation is to hide the implementation details and only provide external access interfaces.

    Encapsulation includes: attribute encapsulation, method encapsulation, class encapsulation, component encapsulation, modular encapsulation, system level encapsulation

2, Benefits of encapsulation

  1. modularization

  2. information hiding

  3. code reuse

  4. Pluggable and easy to debug

  5. With security

    Disadvantages of encapsulation: it will affect the execution efficiency

    Private keyword: access permission modifier. public indicates common, private indicates private, and private attributes or methods can only be accessed in this class

puclick class Test10{
	public static void main (String() args){
		
	}
}
class Person{
	private String name;
	private int age;
	public void setName(String name){
		this.name = name;
	}
	public String getName(){
		return this.name;
	}
}

Member variables and local variables

  1. Different positions in the class

    Member variables: defined in classes

    Local variable: a parameter defined in a method or method

  2. Different locations in memory

    Member variable: in heap memory (member variable belongs to object, and object enters heap memory)

    Local variables: in stack memory (local variables belong to methods, which occupy memory)

  3. Different life cycles

    Member variable: exists with the creation of the object and disappears with the destruction of the object

    Local variable: exists with the method call and disappears with the method call

  4. Different initialization values
    Member variable: has default initialization value and reference type is null

    Local variable: there is no default initialization value. It must be defined and assigned before it can be used

Note: the local variable name can be the same as the member variable name. When using the method, the proximity principle is adopted

Construction method

What is a construction method

  1. Construction method is the method called when the class constructs the object, which is used for object initialization
  2. Constructor is the first method called when instantiating a class object, that is, new

Definition of construction method:

The construction method is defined in the type. The definition format of the construction method: the method name is the same as the class name, and there is no declaration of the return value type.

Object instantiation syntax:

Dog dog = new Dog();// There is a bracket after the new dog, indicating that the method is called. At this time, the called method is the constructor method.

class Dog{
	public Dog(){
		System.out.printLn("The construction method is executed")
	}
	public Dog(String name,int age){
		this.name = name;
		this.age = age;
		System.out.printLn("The construction method with two parameters is implemented")
	}
}

Summary of construction methods

  1. The constructor name is the same as the class name, and there is no return value declaration (including void)
  2. Constructor initializes data (properties) with domain
  3. Each class will contain a default lunch constructor
  4. If there is a constructor displayed in the class, the default constructor is invalid
  5. If there is a displayed construction method and you want to keep the default construction method, you need to write out the displayed ones
  6. There can be more than one construction method, but the parameters are different, which becomes an overload of the construction method
  7. Calling another construction method in the construction method, using this(...), the sentence code must be in the first sentence.
  8. For calls between constructor methods, there must be an exit.
  9. You can use constructor or setter methods to initialize data for an object. Usually, both methods will be retained
  10. A good programming habit is to keep the default constructor. (for convenience, some framework code uses reflection to create objects)
  11. private Dog() {}, the constructor is privatized. When our requirement is to ensure that there is only one object in this class, when does a class need only one object? For example, a tool class (a class without attributes, only behavior) and the tool object is used frequently. The trade-off system uses the memory usage of one object and multiple objects to determine whether the class needs only one object

this keyword

This keyword is the most important concept in java foundation. Use this keyword to complete the following operations:

  • Calling properties in a class
  • Calling a method or constructor in a class
  • Represents the current object

Value passing and reference passing

pass by value

public class valueDemo{
	public static void main(String[] args){
		int x = 10;
		method(x);
		System.out.println("x="+x);
	}
	public static void method(int mx){
		mx = 20;
	}
}

Reference passing

public class RefDemo{
	public static void main(String[] args){
		Duck d = new Duck();
		method(d);
		System.out.println("Duck age ="+d.age);
	}
	public static void method(Duck duck){
		duck.age = 5;
	}
}
class Duck{
	int age = 2; // Omit encapsulation
}

One to one relationship of objects

One to one relationship between two objects:

For example:

A Hero versus a weapon

public class test10 {
    public static void main(String[] args){
        Hero hero = new Hero();
        hero.setName("Lv Bu");
        hero.setAge(22);
        Weapon weapon = new Weapon();
        weapon.setName("Fang Tianhua Halberd");
        hero.setWeapon(weapon);
        weapon.setHero(hero);
    }
}
class Hero{
    private String name;
    private int age;
    private Weapon weapon;

    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }

    public String getName() {
        return name;
    }

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

    public void setWeapon(Weapon weapon) {
        this.weapon = weapon;
    }

    public Weapon getWeapon() {
        return weapon;
    }
}
class Weapon{
    private String name;
    private Hero hero;

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

    public String getName() {
        return name;
    }

    public Hero getHero() {
        return hero;
    }

    public void setHero(Hero hero) {
        this.hero = hero;
    }
}

static keyword

Function of static keyword:

  1. Use the static keyword to decorate an attribute

    A keyword declared as static is essentially a global variable

  2. Use the static keyword to decorate a method

    Usually, a given method is defined as static in a class, that is, this method can be called without the object of this class

  3. Use the static keyword to decorate a class (inner class)

  • Static variables or methods do not belong to objects and depend on classes
  • Static variables are global variables. The life cycle is from the time the class is loaded to the end of the program
  • There is only one copy of static variables stored in the static method area
  • Static variables are shared by all objects of this class
  • It is recommended not to use the object name to call static data, but directly use the class name to call

Methods declared as static have the following limitations:

They can only call other static methods.

They can only access static data.

They cannot reference this or super in any way.

When to use static?

If all objects have common properties or methods, we should define them as static.

main method analysis

//Main method:
public static void main(String[] args){
	//Code block
}

public: shared, maximum access rights

Static: static, without creating objects

void: indicates that there is no return value and there is no need to return the result to the JVM

main: method name, fixed method name

String[] args: indicates that the parameter is a string array

Code block

Common code block

Code blocks written directly in methods are ordinary code blocks

Example:

public class Demo1{
	public static void main(String[] args){
		{
			//Common code block
			String info = "local variable-1";
			System.out.println(info);
		}
		String info = "local variable-2";
		System.out.println(info);
	}
}

A building block is a block of code defined in a class

class Demo{
	{
		//Code block
		System.out.println("Tectonic block")
	}
	public Demo(){
		System.out.println("Construction method")
	}
}

Code blocks declared using static in a class are called static code blocks

When it is called (creating an object) for the first time, it will be executed only once, which is better than the execution of building blocks

class Demo{
	{
		System.out.println("Tectonic block")
	}
	static{
		System.out.println("Static code block")
	}
	public Demo(){
		System.out.println("Construction method")
	}
}

Synchronous code block

Singleton design pattern

Singleton design pattern: ensure that a class has only one instance and provide a global access point to access it.

  1. Construction method privatization
  2. Declare an object of this class
  3. Provide an external static method to obtain object instances

Two implementation methods:

1. Hungry Chinese style: when the getInstance method is called for the first time, the object is created and released after the program ends

class Singleton1{
	private Singleton1(){}
	private static Singleton1 s = new Singleton1();
	public static Singleton1 getInstance(){
		return s;
	}
	public void print(){
		System.out.println("test method")
	}
}

2. Lazy: after the class is loaded, the object is created until the end of the program

class Singleton2{
	private Singleton2(){}
	private static Singleton2 s;
	public static Singleton2 getInstance(){
		if(s==null){
			s = new Singleton2();
		}
		return s;
	}
	public void print(){
		System.out.println("test method")
	}
}

Object array and management

Object array is that each element in the array is an object of class. When assigning values, first define the object, and then copy the object directly to the array.

Example:

Chicken[] cs = new Chicken[10];

Use the object array to realize the management of multiple chickens.

Basic concepts of inheritance

Inheritance is the process of creating a new class from an existing class

  1. Inheritance is one of the three characteristics of object-oriented
  2. The inherited class becomes the parent class (superclass), and the class that inherits the parent class is called the child class (derived class)
  3. Inheritance means that one object directly uses the properties and methods of another object
  4. Code reuse can be achieved through inheritance

Protected access modifier, which is used in inheritance relationship. Properties or methods modified with protected in parent class can be inherited by subclasses

When creating a subclass object, the constructor of the parent class will also be called. Why?

Because the subclass needs to use the data of the parent class, it needs to initialize the data through the construction method of the parent class,

If the default constructor is used when passing a subclass object, the default constructor of the parent class will also be called

If you create a subclass object, the default constructor of the parent class will be called

class Dog{
	protected name;
    protected age;
    public void eat(){
        System.out.println("It's time to start cooking")
    }
}
class HomeDog extends Dog{
    public void say(){
        System.out.println("I'm a dog")
    }
}

Inheritance summary

  1. Inheritance occurs between multiple classes
  2. Inheritance uses the keyword extends
  3. JAVA can only inherit in single layer, and multi-layer inheritance is allowed
  4. The inherited class is called the parent class (superclass), and the class that inherits the parent class is called the subclass (derived class)
  5. Non private properties and methods in the parent class can be inherited by subclasses
  6. Protected (protected access modifier). The modified property or method can be inherited by subclasses
  7. Constructor cannot be inherited
  8. Creating an object will call the constructor. Calling the constructor does not necessarily create this kind of object
  9. Instantiating a subclass object will first call the construction method of the parent class. If there is no default construction method in the parent class, the subclass must call the parameterized construction method of the parent class through super(...), and super can only be in the first sentence of the subclass construction method

Benefits of inheritance:

  1. Improve code reusability
  2. Improve code maintainability
  3. Making the relationship between classes is the premise of polymorphism

Disadvantages of inheritance

Enhanced coupling between classes

Development principle: high cohesion, low coupling

Method override

In Java, subclasses can inherit the methods in the parent class without rewriting the same methods. However, sometimes subclasses do not want to inherit the methods of the parent class intact, but want to make certain modifications, which requires method rewriting. Method overrides are also called method overrides.

In subclasses and parent classes, after overriding the method, the created object type shall prevail when calling, and whose method will be called.

Some features of method override:

  1. Occurs in the child parent class. The return value, method name and parameter list of the two methods overridden by the method must be exactly the same (the child class overrides the method of the parent class)
  2. The exception thrown by a subclass cannot exceed the exception thrown by the corresponding method of the parent class (the subclass exception cannot be greater than the parent exception)
  3. The access level of the subclass method cannot be lower than that of the corresponding method of the parent class (the access level of the subclass cannot be lower than that of the parent class)
  4. If the method in the parent class is modified with any modifiers such as private, static and final, it cannot be overridden by the child class

Why rewrite methods? Or what is the purpose of method rewriting?

If the method inherited by the subclass from the parent class cannot meet the specific needs of the subclass, the subclass needs to rewrite the corresponding method in the parent class, which is also the embodiment of program extension

class Dog{
	protected name;
    protected age;
    public void eat(){
        System.out.println("It's time to start cooking")
    }
}
class HomeDog extends Dog{
    public void eat(){
        System.out.println("I like rice")
    }
}

super keyword

super can complete the following operations:

  1. Using super to call properties in the parent class, you can get information from the parent class instance
  2. Using super to call the method in the parent class, you can delegate the parent object to help accomplish something
  3. When super is used to call the constructor in the parent class (in the form of super (argument)), the corresponding constructor in the parent class must be called in the first statement of the subclass constructor. If it is not displayed, the parameterless constructor of the parent class will be called by default, such as super()

Application examples of inheritance

  1. Define a Cosmetic class

  2. Define a cosmetic management class (cosmoticmanager)

    Realize the purchase function

    It can output all cosmetics information

  3. Use inheritance to realize a function that can sort and output all cosmetics by unit price

  4. Use inheritance to realize a function that only outputs imported cosmetics

import java.util.Arrays;

public class java12 {
    public static void main(String[] args) {
        ImportCosmeticManager cm = new ImportCosmeticManager();
        cm.add(new Cosmetic("Chanel","Import",1000));
        cm.add(new Cosmetic("Y.S.L","Import",800));
        cm.add(new Cosmetic("Dabao","domestic",20));
        cm.add(new Cosmetic("a riot of colour","domestic",10));
        cm.printAll();

    }
}
class CosmeticManager{
    protected Cosmetic[] cs = new Cosmetic[4];
    protected int count=0;
    // Purchase function
    public void add(Cosmetic c){
        if(count>=cs.length){
            int newLen = cs.length*2;
            cs = Arrays.copyOf(cs,newLen);
        }
        cs[count] = c;
        count++;
    }
    public void printAll(){
        for (int i=0;i<cs.length;i++){
            cs[i].getInfo();
        }
    }
}
// Export of imported goods
class ImportCosmeticManager extends CosmeticManager{
    public void printAll(){
        for(int i=0;i<count-1;i++){
            if("Import".equals(cs[i].getType())){
                cs[i].getInfo();
            }
        }
    }
}
//Sort by price
class SortCosmeticManager extends CosmeticManager{
    public void printAll(){
        Cosmetic[] temp = Arrays.copyOf(cs,count);
        Cosmetic c = null;
        for(int i = 0;i<count-1;i++){
            for(int j = 0;j<count-i-1;j++){
                if(temp[j].getPrice()>temp[j+1].getPrice()){
                    c = temp[j];
                    temp[j] = temp[j+1];
                    temp[j+1] = c;
                }
            }
        }
        for(Cosmetic n:temp){
            n.getInfo();
        }
    }
}
// Makeup
class Cosmetic{
    private String name;// brand
    private String type;// Imported or domestic
    private int price;// Price

    public Cosmetic(String name,String type,int price){
        this.name = name;
        this.type = type;
        this.price = price;
    }

    public String getName() {
        return name;
    }

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

    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }

    public int getPrice() {
        return price;
    }

    public void setPrice(int price) {
        this.price = price;
    }

    public void getInfo(){
        System.out.println("name="+getName()+",type="+getType()+",price="+getPrice());
    }
}

final keyword

Use the final keyword to complete the following operations:

  1. Declare a constant using the final keyword

    Modify attributes or modify local variables (final variables), also known as constants.

  2. Declare a method using the final keyword

    This method is the final method and can only be inherited by subclasses, but cannot be overridden by subclasses.

  3. Declare a class using the final keyword

    This class is transformed into the final class. For classes without subclasses, the final modified class cannot be inherited.

  4. Use final in the method parameter. The value of the parameter cannot be modified inside the method (explained in detail in the internal class)

abstract class

Basic concepts of abstract classes

  1. Many objects with the same characteristics and behaviors can be abstracted into a class, and many classes with the same characteristics and behaviors can be abstracted into an abstract class
  2. The class declared with the abstract keyword is abstract
abstract class Animal{
	public abstract void move() // Method declaration. Abstract methods have only declarations but no implementations
}
// Concrete classes that inherit abstract classes must implement all abstract methods
abstract class Person extends Animal{
	public abstract void eat()
}
class Man extends Person{
	public void move(){}
	public void eat(){}
}
  • Abstract classes can have no abstract methods. Classes with abstract methods must be abstract classes
  • A non abstract class inherits from an abstract class. An abstract class must implement all abstract methods
  • An abstract class can inherit an abstract class, and it can not be an abstract method of a parent class
  • Abstract classes can have method implementations and properties
  • Abstract classes cannot be instantiated
  • Abstract classes cannot be declared final
  • Abstract classes can have constructors

Interface

Concept of interface

  1. An interface is the specification and definition of a group of behaviors without implementation
  2. Using the interface can make our program more conducive to change
  3. Interface is one of the quintessence of object-oriented programming system
  4. Object oriented design principle: interface based programming

Interface definition format

Interface interface name{

Global constant;

Abstract methods;

​ }

interface IEat{
 	// public abstract void eat(); // Only abstract methods can be defined in an interface
 	void eat(); // The method defined in the interface does not have a declaration modifier. It defaults to public abstract
 	int Num = 10; // constant
}
interface IRun{
    void run()
}
// Multiple interfaces can be inherited (Note: classes can only be inherited individually)
interface ISleep extends IEat,IRun{
    void sleep();
}
class Girl implements ISleep,IEat{
    // Concrete implementation
}


Rules for using interfaces:

  1. Define an interface using the interface keyword
  2. In an interface, only constants and abstract methods can be defined. After JDK1.8, the default implementation method can be defined
  3. Interfaces can inherit multiple interfaces
  4. A concrete class implementation interface uses the implements keyword
  5. A class can implement multiple interfaces
  6. Abstract classes can implement methods that do not implement interfaces
  7. The method defined in the interface does not declare an access modifier. It defaults to public
  8. An interface cannot have a constructor

Object oriented design principles:

  1. It is closed for modification and open for extension
  2. Interface oriented programming

Polymorphism

Polymorphism is one of the three characteristics of object-oriented

What is polymorphism?

Multiple specifications of objects in the running process

Polymorphism can be roughly divided into two categories:

  1. Method overloading and rewriting
  2. Polymorphism of objects

For example:

//Use the reference of the parent class to point to the child class object (use the large type to accept the small type, and transform upward and automatically)

Chicken home = new HomeChicken();

Conclusion:

When programming, you write code for abstract types to become the parent class of object-oriented programming (or interface oriented programming), which is usually defined as abstract classes and interfaces

Polymorphism of objects

Object polymorphism is derived from multiple classes in an inheritance relationship

Upward Transformation: convert a child class instance to a parent class instance

Format: parent class, parent class object = child class instance: = > auto convert

Take the basic data type operation as an example: int i = 'a';

(because the capacity of char is smaller than int, it can be completed automatically)

**Downward Transformation: * * convert parent class instances to child class instances

Format: subclass subclass object = (subclass) parent class instance: Cast

Take the basic data type operation as an example: char c = (char)97;

Because the integer is 4 word streets larger than char2 bytes, it needs to be forced to complete

Polymorphism summary

  1. Method overloading and rewriting are the expression of method polymorphism
  2. Multiple subclasses are multiple forms in the parent class
  3. The parent class reference can point to the child class object, which is automatically converted
  4. The reference of a subclass to a parent class needs to be cast (Note: the type will not report an exception)
  5. In the actual development, try to use the parent class reference (which is more conducive to expansion)

instanceof keyword

instanceof is used to check whether it is a specified type. It is usually used when casting a parent class reference to a child class reference to avoid type conversion exceptions

The syntax format is as follows:

Object instanceof type -- return boolean type value

Example:

if(homeChicken instanceof Chicken){}

This statement is generally used to judge whether an object is an instance of a class. It returns true or false

Design rules for parent classes

Through the instanceof keyword, we can easily check the type of object, but if there are too many subclasses of a parent class, such judgment is still cumbersome. How to design a parent class?

  1. The parent class is usually designed as an abstract class or interface, in which the interface is given priority. If the interface cannot be satisfied, the abstract class is considered
  2. A concrete class does not inherit another concrete class as much as possible, which has the advantage that there is no need to check whether the object is a parent object

Abstract class application template method pattern

Template method: defines the skeleton of an algorithm in operation, and delays the implementation of some variable parts to subclasses. The template method pattern allows subclasses to redefine some specific steps of an algorithm without changing the structure of the algorithm.

public class test12 {
    public static void main(String[] args) {
        UserManager um = new UserManager();
        um.action("admin","del");
    }
}
abstract class BaseManager{
    public void action(String name,String method){
        if("admin".equals(name)){
            execute(method);
        }else{
            System.out.println("You do not have operation permission, please contact the administrator");
        }
    }
    public abstract void execute(String execute);
}
class UserManager extends BaseManager{
    public void execute(String method){
        if("add".equals(method)){
            System.out.println("Execute add method");
        }else if("del".equals(method)){
            System.out.println("Execute delete method");
        }
    }
}

Application policy mode of interface

Strategy Pattern defines a series of algorithms, encapsulates each algorithm and can be replaced with each other. The Strategy Pattern allows the algorithm to transform independently from the customer application using it

OO design principles:

  1. Interface oriented programming (Abstract oriented programming)
  2. Package change
  3. Use more combination and less inheritance
import sun.awt.geom.AreaOp;

//Strategy mode
public class test1 {
    public static void main(String[] args){
        BaseSerive user = new UserSerive();
        user.setIsSave(new NetSave());
        user.add("user");
    }
}
interface IsSave{
    public void save(String data);
}
class FileSave implements IsSave{
    @Override
    public void save(String data) {
        System.out.println("Save data to a file"+data);
    }
}
class NetSave implements IsSave{
    @Override
    public void save(String data) {
        System.out.println("Save data to the network"+data);
    }
}

abstract class BaseSerive{
    private IsSave isSave; // Private property

    public void setIsSave(IsSave isSave) {
        this.isSave = isSave;
    }

    public void add(String data) {
        System.out.println("Verify data validity");
        isSave.save(data);
        System.out.println("Data saved successfully");
    }
}

class UserSerive extends BaseSerive{

}

Objec class

The object class is the root class of the class hierarchy

Each class uses Object as its superclass. All objects (including arrays) implement the methods of this class

All classes are subclasses of the Object class.

toString method

Returns a string representation of the object

Typically, the toString method returns a string that "represents" the object as text. The result should be a concise and easy to read information expression. It is recommended that all subclasses override this method.

class Student{
	private String name;
	private int sid;
	private int age;
	public Student(){}
	public Student(int sid,String name,int age){
		this.name = name;
		this.sid = sid;
		this.age age;
	}
	// Override the toString method in the Object class
	public String toString(){
		return "sid="+sid+",name="+name+",age="+age;
	}
}

equals method

Indicates whether some other object is "equal" to this object. The equals method implements equality on non empty object references:

Reflexivity symmetry transitivity consistency

finalize method

This method is called by the object's garbage collector when the garbage collector determines that there are no more references to the object. Subclasses override the finalize method to configure system resources or perform other cleanup

getClass method

Returns the runtime class of the secondary Object

Simple factory mode

The simple factory pattern is a factory object that determines which product class instance to create. The simple factory pattern is the simplest pattern used in the factory pattern family.

// Use factories to reduce dependence between the two
// The coupling between the user and the user generates dependency. When the user changes, it will affect the user
class ProductFactory{
    public static Product getProduct(String name){
        if("phone".equals(name)){
            return new Phone();
        }else if("computer".equals(name)){
            return new Computer;
        }else{
            return null 
        }
    }
}
interface Product{
	public void work();
}
class Phone implements Product{
	public void work(){
		System.out.println("The phone starts working...")
	}
}
class Computer implements Product{
	public void work(){
		System.out.println("The computer starts working...")
	}
} 

Static proxy mode

Proxy mode: provides a proxy for other objects to control access to this object

The proxy model is simply the representative of "real objects". It refers to a certain degree of indirectness when accessing objects, because this indirectness can be used for a variety of purposes.

public class test13 {
    public static void main(String[] args) {
        UserAction userAction = new UserAction();
        ActionProxy proxy = new ActionProxy(userAction);
        proxy.doAction();
    }
}
interface Action{
    public void doAction();
}
class ActionProxy implements Action{
    private Action target;
    public ActionProxy(Action target){
        this.target = target;
    }
    @Override
    public void doAction() {
        long startTime = System.currentTimeMillis();
        target.doAction();
        long endTime = System.currentTimeMillis();
        System.out.println("Total time"+(endTime-startTime));
    }
}
class UserAction implements Action{
    @Override
    public void doAction() {
        for(int i = 0;i < 100;i++){
            System.out.println("User starts working...");
        }
    }
}

Adapter mode

Adapter mode: converts the interface of a class into another interface desired by the customer. Adapter mode enables classes that cannot work together due to interface incompatibility to work together

oo design principles:

  1. Interface oriented programming (Abstract oriented programming)
  2. Package change
  3. Use more combination and less inheritance
  4. It is closed for modification and open for extension
public class test14 {
    public static void main(String[] args) {
        PowerA powerA = new PowerAImp1();
        PowerB powerB = new PowerBImp1();
        Adapter adapter = new Adapter(powerB);
        work(adapter);
    }
    public static void work(PowerA a){
        System.out.println("Connecting...");
        a.insert();
        System.out.println("end-of-job...");
    }
}
class Adapter implements PowerA{
    private PowerB powerB;
    public Adapter(PowerB powerB){
        this.powerB = powerB;
    }

    @Override
    public void insert() {
        powerB.connect();
    }
}
interface PowerA{
    public void insert();
}
class PowerAImp1 implements PowerA{
    @Override
    public void insert() {
        System.out.println("Power Supply A start-up");
    }
}

interface PowerB{
    public void connect();
}
class PowerBImp1 implements PowerB{
    @Override
    public void connect() {
        System.out.println("Power Supply B start-up");
    }
}

Inner class

An inner class is a class defined inside a class

Member inner class

The format is as follows:

class Outer{

​ class Inner{}

}

Compiling the appeal code produces two files:

Outer.class and Outer$Inner.class

Method inner class

Internal classes can be defined in methods in addition to being members of a class

be careful:

  1. A method inner class can only be instantiated within the method that defines the inner class, and cannot be instantiated outside this method
  2. Method inner class objects cannot use non final local variables of all methods of the inner class

Static inner class

Define a static inner class inside a class

Static means that the internal class can be accessed like other static members when there is no external class object. Static nested classes can only access static members and methods of external classes

Anonymous Inner Class

An anonymous inner class is an inner class without a name.

There are three situations for anonymous inner classes:

  1. Inherited anonymous inner class
  2. Interface style anonymous inner class
  3. Parameterized anonymous inner class

When using anonymous inner classes, remember the following principles:

  1. There cannot be a constructor. There can only be one instance
  2. You cannot define any static members or static methods
  3. Cannot be public,protected,private,static
  4. It must be behind new to implicitly implement an interface or a class
  5. Anonymous inner classes are local, so all restrictions on local inner classes apply to them
public class test15 {
    public static void main(String[] args) {
        Outer outer = new Outer();
        outer.innerPrint();
        outer.show();
        Outer.Inner3 inner3 = new Outer.Inner3();
        inner3.print();
        outer.print1();
        outer.print2();
        outer.print3(new Eat() {
            @Override
            public void eat() {
                System.out.println("eat:Parametric anonymous inner class");
            }
        });
//        Outer.Inner inner = outer.new Inner();
//        inner.print();
    }
}
class Outer{
    private String name;
    public void innerPrint(){
        Inner inner = new Inner();
        inner.print();
    }
    // Member inner class
     private class Inner{
        public void print(){
            System.out.println("Member inner class");
        }
    }
    // Method inner class
    public void show(){
        class Inner2{
            public void print(){
                System.out.println("Method inner class");
            }
        }
        Inner2 inner2 = new Inner2();
        inner2.print();
    }
    // Static inner class
    static class Inner3{
        public void print(){
            System.out.println("Static inner class");
        }
    }
    // Anonymous Inner Class 
    public void print1(){
        Cat cat = new Cat(){
            @Override
            public void eat() {
                System.out.println("eat:Inherited anonymous inner class");
            }
        };
        cat.eat();
    }
    public void print2(){
        Eat eat = () -> System.out.println("eat:Interface anonymous inner class");
        eat.eat();
    }
    public void print3(Eat eat){
        eat.eat();
    }
}
abstract class Cat{
    public abstract void eat();
}
interface Eat{
    void eat();
}

Question: local internal classes must be modified with final to access local variables. Why?

When calling this method, if the local variable is not decorated with final, its life cycle is the same as that of the method. When the method is called, it will be put into the stack. After the method ends, it will pop up and the local variable will disappear. If the local internal class object does not disappear immediately, it is obviously impossible to use this local variable, If the final modification is used, it will enter the constant pool when the class is loaded. Even if the method bounces the stack and the constant of the constant pool is still there, it can continue to be used

c,protected,private,static
4. It must be behind new to implicitly implement an interface or a class
5. Anonymous inner classes are local, so all restrictions on local inner classes are effective for them

public class test15 {
    public static void main(String[] args) {
        Outer outer = new Outer();
        outer.innerPrint();
        outer.show();
        Outer.Inner3 inner3 = new Outer.Inner3();
        inner3.print();
        outer.print1();
        outer.print2();
        outer.print3(new Eat() {
            @Override
            public void eat() {
                System.out.println("eat:Parametric anonymous inner class");
            }
        });
//        Outer.Inner inner = outer.new Inner();
//        inner.print();
    }
}
class Outer{
    private String name;
    public void innerPrint(){
        Inner inner = new Inner();
        inner.print();
    }
    // Member inner class
     private class Inner{
        public void print(){
            System.out.println("Member inner class");
        }
    }
    // Method inner class
    public void show(){
        class Inner2{
            public void print(){
                System.out.println("Method inner class");
            }
        }
        Inner2 inner2 = new Inner2();
        inner2.print();
    }
    // Static inner class
    static class Inner3{
        public void print(){
            System.out.println("Static inner class");
        }
    }
    // Anonymous Inner Class 
    public void print1(){
        Cat cat = new Cat(){
            @Override
            public void eat() {
                System.out.println("eat:Inherited anonymous inner class");
            }
        };
        cat.eat();
    }
    public void print2(){
        Eat eat = () -> System.out.println("eat:Interface anonymous inner class");
        eat.eat();
    }
    public void print3(Eat eat){
        eat.eat();
    }
}
abstract class Cat{
    public abstract void eat();
}
interface Eat{
    void eat();
}

Question: local internal classes must be modified with final to access local variables. Why?

When calling this method, if the local variable is not decorated with final, its life cycle is the same as that of the method. When the method is called, it will be put into the stack. After the method ends, it will pop up and the local variable will disappear. If the local internal class object does not disappear immediately, it is obviously impossible to use this local variable, If the final modification is used, it will enter the constant pool when the class is loaded. Even if the method bounces the stack and the constant of the constant pool is still there, it can continue to be used

Keywords: Java

Added by LoganK on Sat, 27 Nov 2021 02:01:43 +0200