Object-oriented programming (JAVA) review notes (on)

Article Directory

1. Basic knowledge of JAVA language

The Java language is an object-oriented programming language.
In addition to object-oriented features, the Java language also has excellent advantages in many aspects such as security, platform independence, support for multithreading, and memory management.

insert image description here

Computer programming :

  1. abstract the problem
  2. Express in computer language, use machine to solve

Object-oriented thinking Object
-oriented thinking
regards objective things as objects with state and behavior, finds out the common state and behavior of the same type of objects through abstraction, and forms a class.

For example:
To build a car class, it is necessary to extract the common state and behavior of all car objects.
The state is represented by variables, and the behavior is represented by methods.

class Car {
    
    
    int color_number;  
    int door_number;
    int speed;    ……
    void brake() {
    
    }
    void speedUp() {
    
    };
    void slowDown() {
    
    };……
}  

The Benefits of Object-Oriented Technology to Software Development

  1. reusability
  2. reliability

Basic Features of Object-Oriented Languages

  1. abstraction and encapsulation
  2. Inheritance
  3. polymorphism

Features of the Java language:

  1. object oriented
  2. Security
    Java does not support pointers
    Java's internal security measures
  3. Platform independence
    Compiled bytecode corresponds to the Java virtual machine, so it can run on different platforms
  4. Multithreaded
    Java was the first high-level language to provide built-in multithreading support at the language level
  5. Memory management
    Java automatically manages memory and performs garbage collection

The difference between Java and C++
There is no preprocessing function such as #include and #define in Java, and other classes and packages are included in the import statement;
there is no structure, union and typedef in Java;
there is no function that is not a member of a class in Java, and there is no pointer And multiple inheritance, Java only supports single inheritance;
goto is disabled in Java, but goto is still a reserved keyword;
there is no operator overloading in Java;
there is no global variable in Java, you can define public and static data members in the class to achieve the same function ;

The smallest unit that makes up a Java program is a class, which encapsulates data and methods for processing data.
For most commonly used functions, there are a large number of compiled and tested classes. The collection of these classes is the Java class library.
The Java class library is mainly provided with the compiler, and some class libraries are provided by independent software developers.

The process of compiling and executing Java programs:
write once and run everywhere
insert image description here
JAVA platform:
insert image description here
Java APIs (application program interface)
compiled Java code standard library that can be used in the program.
Java VM (virtual machine) Virtual Machine
Java programs are executed (or interpreted) by Java virtual machine programs.

Java Platform Java2 SDK (Software Development Kit):

insert image description here
Java development tools include
Javac : a Java compiler used to compile java programs into Bytecode.
Java : A Java interpreter that executes java applications that have been converted into Bytecode.
Jdb : Java debugger, used to debug java programs.
Javap : decompile, restore class files back to methods and variables.
Javadoc : Documentation generator that creates HTML files.
Appletviwer : Applet interpreter, used to explain the java applet that has been converted into Bytecode.

insert image description here
insert image description here
Java program example:

The Java program running on the client Java virtual machine
can be read and written in the client machine
Can use its own main window, title bar and menu
The program can be large or small The main class must have a main method main
(
), as the entry point for the program to run.

A Java source code file is called a compilation unit.
There can only be one public class in a compilation unit, and the class name is the same as the file name. Other classes in the compilation unit are often auxiliary classes of the public class. After compilation, each class will generate a class file.

insert image description here
Compile and run the program with the following commands:

javac	MyClass.java
java  MyClass

variables and constants

Variable
An item named by an identifier.
Every variable has a type, such as int or Object, and a variable has a scope.
The value of a variable can be changed.
Constant
A constant cannot be changed once it is initialized.

Identifier
An identifier is a name that corresponds to a location (address) in memory. The
first character of an identifier must be one of the following characters:

uppercase letter (AZ)
lowercase letter (az)
underscore (_)
dollar sign ($)

The second and subsequent characters of the identifier must be:

Any character from the above list
Numeric characters (0-9)

integer

byte 8 bits
short 16 bits
int 32 bits
long 64
char 16

Integer operations
Comparison operators (relational operators)

Arithmetic comparison operators <, <=, >, and >=
Arithmetic equality comparison operators == and !=

arithmetic operator

Unary operators + and -
+,- *, /, and % (remainder)
increment/decrement operators ++/–
shift operators <<, >>, and >>>
bitwise operators ~, & , |, and ^

Conditional operator? :
Type conversion operator
String concatenation operator +

floating point number
float

Single-precision floating-point number
32-bit
-m 2 e ~ m 2 e
m is a positive integer less than 2 24
e is an integer between -149 and 104 (inclusive)

double

Double-precision floating-point number
64-bit
m 2 e ~ m 2 e
m is a positive integer less than 2 53
e is an integer between -1045 and 1000 (inclusive)

Floating-point operations
Comparison operators (relational operators)

Arithmetic comparison operators <, <=, >, and >=
Arithmetic equality comparison operators == and !=

arithmetic operator

Unary operators + and -
+,- *, /, and % (remainder)
increment/decrement operators ++/–
shift operators <<, >>, and >>>
bitwise operators ~, & , |, and ^

Conditional operator? :
Type conversion operator
String concatenation operator +

Boolean type and Boolean value
The Boolean type represents a logical quantity and has two values: true and false

boolean operator

Relational operators == and !=
Logical NOT operator !
Logical operators &, ^, and |
Conditional AND and OR operator && and ||
Conditional operator ? :
String concatenation operator +

String - String

String is a
part of the String class JDK standard class collection
String animal = "walrus";

amount of characters

The value that appears directly in the program and is directly used by the compiler.
Integer literal
Decimal: eg: 15
Hexadecimal: eg: 0xff
Octal: eg: 0377

floating point literal

A floating-point literal includes the following parts: Integer part Decimal
point Decimal part Exponent (e or E) type suffix (f or F for float, d or D for double) Examples of float type literals: 1e 1f 2.f .3f 0f 3.1 4f 6.022137e+23f Example of double type text: 1e1 2. .3 0.0 3.1 4 1e-9d 1e137







Boolean literals
The Boolean type has only two values, represented by the literals true and false

Amount of characters

A character literal is expressed as a character or an escape sequence, enclosed in single quotes,
such as 'a' 'Z' '@'
format characters
\ b backspace BS
\ t horizontal tab HT
\ n linefeed LF
\ f form feed FF enter paper key; page skip
\ r carriage return CR
\ "double quote "
\ ' single quote '
\ \ backslash \

string literal

Consists of zero or more characters, enclosed in double quotes
Each character can be represented by an escape sequence
For example:
"" // an empty string
" \ "" // a string containing only "
"This is a string" // 16-character string
"This is a " + "string" //String constant expression, composed of two string constants

arithmetic operator

Operators ++ and –
For example: i++; --j;
unary operators + and –
addition operators + and -
multiplication operators *, /, and %

assignment operator

Simple assignment operator =
compound assignment operator
*= /= %= += -= <<= >>= >>>= &= ^= |=
E1 op= E2 Equivalent to E1 = (T)((E1 ) op (E2)), where T is the type of E1

relational operator

The type of relational expression is always Boolean type (bool).
Arithmetic comparison operators <, <=, >, and >=
type comparison operator instanceof
For example: e instanceof Point //Point is a class

equality operator

equality operator

Numeric equality operators == , !=

Boolean equality operators == , !=

Reference equality operators == , !=

Logical Operators

"AND" operation &&
If both operands are true, the result is true; otherwise, the result is false.
"OR" operation ||
If both operands are false, the result is false; otherwise, the result true
"not" operator!
The type of the operand must be of boolean type
The result of the expression is true if the result of the operand is false, and the result of the expression is false if the result of the operand is true

conditional operator(expression1?expression2:expression3)

First evaluate expression 1
If the value of expression 1 is true, select the value of expression 2
If the value of expression 1 is false, select the value of expression 3

type conversion

Every expression has a type.
If the type of the expression is not appropriate for the context,
it can sometimes cause compilation errors.
Sometimes the language does implicit type conversions.

Example Question
insert image description here
Answer: Incorrect.
Reason: the precision is inaccurate, you should use forced type conversion, as follows: float f=(float)3.4 or float f = 3.4f
in java, the default is int without a decimal point, and the default is double with a decimal point; the
compiler can Automatic upward transformation, such as converting int to long, there is no problem with the system's automatic conversion, because the latter has higher precision, and
double to float cannot be done automatically, so add an f afterwards;

insert image description hereinsert image description here
insert image description here
type conversion
assignment conversion

typecasts the expression to the type of the specified variable

method call conversion

Applies to every parameter in a method or constructor call

forced conversion

converts an expression to the specified type

For example (float) 5.0
string conversion
Any type (including null type) can be converted to string type
Only when one operand is String type, it is applicable to the operand of + operator

Numeric promotion
Converts the operands of an arithmetic operator to a common type
Unary numeric promotion

If an operand is of type byte, short, or char, unary numeric promotion converts it to type int via a widening conversion

binary number boost

Binary numeric promotions are applied to the operands of specific operators *, /, %, +, -, <, <=, >, >=, ==, !=, &, ^, | and?: when
necessary Convert operand types using widening conversions

standard input and output

Standard input stream System.in
Standard output stream System.out
eg

System.out.println("Hello world!");

array

Array Elements
Variables in an array are referred to as elements of the array
Elements do not have names, passed 数组名字and 非负整数下标值referenced to array elements.
Each array has a member variable modified by public final: length, that is, the number of elements the array contains (length can be a positive number or zero)

array declaration

Declaration (Declaration)
does not need to specify the number of array elements when declaring an array, and does not allocate memory space for the array elements. It
cannot be used directly, and must be initialized to allocate memory before use.

Type[ ] arrayName;   
//例如:
int[] intArray; 
String[]  stringArray; 
Type  arrayName[ ];   
//例如:
int intArray[];  
String  stringArray[];

Array creation

Use keywords newto form an array creation expression, and you can specify the type of array and the number of array elements. The number of elements can be a constant or a variable. Each element of
an array of basic types is a variable of a basic type; each element of an array of reference types is a reference to an object.

Supplement:
Java variables are divided into two categories: basic data types and reference data types.
Among them, there are four types and 8 types of basic type variables:
byte short int long float double char boolean
except for the 8 basic data type variables, other variables are all reference data types, such as classes, interfaces, arrays, etc.

The basic data type has only one storage space, and the specific data value is stored in the stack.

The reference data type has two storage spaces, one in the stack (Stack) and one in the heap (heap). The object entity is stored in the heap (use the new keyword, which means opening a new storage space in the heap), and the stack stores the first address of the object's location in the heap. Reference type variables are similar to pointers in C/C++ .

Reference : A reference type variable (a piece of memory space in the stack) stores the first address of an object of this type in the heap. It is also called a reference type variable that points to an object of this type. Through this variable, you can operate data in the object.

The difference between the heap and the stack is:
the stack is automatically allocated by the system, while the heap is opened by human application; the
space obtained by the stack is small, while the space obtained by the heap is larger;
the stack is automatically allocated by the system, and the speed is faster, while the general speed of the heap is relatively Slow;
the stack is a continuous space, while the heap is a discontinuous space.

Create an array:

arryName=new Type[componets number];
//例如:
	int[] ai;    ai=new int[10];
	String[] s;   s=new String[3];
//或者可以将数组的声明和创建一并执行
	int ai[]=new int[10];
//可以在一条声明语句中创建多个数组 
	String[]  s1=new String[3],  s2=new String[8];

Initialization of array elements

When declaring the array name, the initial value of the array is given, and the program will use the initial value of the array to create the array and initialize its elements

int a[]={
    
    22, 33, 44, 55};

When creating an array, if no initial value is specified, the array is given the default initial value.
Basic type numerical data, the default initial value is 0;
boolean type data, the default value is false;
the default value of reference type element is null.
Programs can also change array element values ​​after the array has been constructed

array reference

An element of an array is referenced by the following expression:

arrayName[index]

Array subscripts must be int, short, byte, or char.
Subscripts start counting from zero.
The number of elements is the length of the array, which can arryName.lengthbe referenced
element. The maximum value of subscripts is length – 1. If it exceeds the maximum value, it will An array out-of-bounds exception ( ArrayIndexOutOfBoundsException) will be generated
insert image description here
. Example:

public class MyArray {
    
    
    public static void main(String[] args){
    
    
        int myArray[];                  //声明数组
        myArray=new int[10];            //创建数组
        System.out.println("Index\t\tValue");
        for(int i=0; i<myArray.length;i++)
            System.out.println(i+"\t\t"+myArray[i]);
        //证明数组元素默认初始化为0
        //myArray[10]=100;      //将产生数组越界异常
    } 
}

The array name is a reference:
Example

public class Arrays 
{
    
       public static void main(String[] args) 
    {
    
      int[] a1 = {
    
     1, 2, 3, 4, 5 }; 
        int[] a2; 
        a2 = a1; 
        for(int i = 0; i < a2.length; i++)   a2[i]++; 
        for(int i = 0; i < a1.length; i++) 
            System.out.println( "a1[" + i + "] = " + a1[i]); 
    } 
} 

Running result:
a1[0] = 2
a1[1] = 3
a1[2] = 4
a1[3] = 5
a1[4] = 6

insert image description here
Array copy :

	public static void arraycopy(Object source , int srcIndex , Object dest , int destIndex , int length ) 

insert image description here

例子
public class ArrayCopyDemo 
{
    
     public static void main(String[] args) 
  {
    
     char[] copyFrom = {
    
     'd', 'e', 'c', 'a', 'f', 'f', 'e', 
                                   'i', 'n', 'a', 't', 'e', 'd'}; 
    char[] copyTo = new char[7]; 
    System.arraycopy(copyFrom, 2, copyTo, 0, 7); 
    System.out.println(new String(copyTo));
   } 
} 

copy iscaffein

Multidimensional Arrays

Declaration and construction of two-dimensional array

int[ ][ ] myArray ;
//myArray 可以存储一个指向2维整数数组的引用。其初始值为null。
int[ ][ ] myArray = new int[3][5] ;
//建立一个数组对象,把引用存储到myArray。这个数组所有元素的初始值为零。
int[ ][ ] myArray = {
    
     {
    
    8,1,2,2,9}, {
    
    1,9,4,0,3}, {
    
    0,3,0,0,7} };
//建立一个数组并为每一个元素赋值。

length of multidimensional array

二维数组的长度
	class UnevenExample2
	{
    
     public static void main( String[ ] arg )
 	   {
    
     int[ ][ ] uneven = 
	        {
    
     {
    
     1, 9, 4 },
	          {
    
     0, 2},
	          {
    
     0, 1, 2, 3, 4 } };
   	      System.out.println("Length is: " + 	uneven.length );
  	    }
	}

Running result:
Length is: 3

// 数组的长度 (行数)
    System.out.println("Length of array is: " + uneven.length );
    // 数组每一行的长度(列数)
    System.out.println("Length of row[0] is: " + uneven[0].length );
    System.out.println("Length of row[1] is: " + uneven[1].length );
    System.out.println("Length of row[2] is: " + uneven[2].length );
  }
}

运行结果:
Length of array is: 3
Length of row[0] is: 3
Length of row[1] is: 2
Length of row[2] is: 5

2. Basic concepts of classes and objects

An Overview of Object-Oriented Programming Methods

Object-oriented programming
Compared with structured programming methods, it is more in line with the human way of thinking about the real world.
It has become the mainstream direction of programming.
The main concepts involved

Abstract
Encapsulation
Inheritance
Polymorphism

Objects
in the real world

Everything is an object.
Each has its own attributes, and presents its own behavior to the outside world.

in the program

Everything is an object.
All have identity (identity), attributes and behavior (methods)
through one or more variables to save their state.
Through the method (method) to achieve his behavior.

kind

Group objects with the same or similar properties and behaviors into one class.
A class can be regarded as an abstraction of an object, representing the common properties and behaviors of such objects.
In object-oriented programming, every object belongs to a specific class.

structured programming

It usually consists of several program modules , and each program module can be a subroutine or a function.
Data and functions are separated, and the code is difficult to maintain and reuse.

object-oriented programming

The basic unit of composition is a class.
When the program is running, the object is generated by the class, and the object is the core of the object-oriented program.
Objects communicate by sending messages and cooperate with each other to complete corresponding functions.

abstract

Ignore aspects of the problem that are not relevant to the current goal in order to give fuller attention to aspects that are relevant to the current goal
Example: Clock
Data (property)
int Hour; int Minute; int Second;
method (behavior)
SetTime(); ShowTime();

encapsulation

It is an information concealment technology.
Use abstract data types to encapsulate data and data-based operations.
The user can only see the encapsulated interface information of the object, and the internal details of the object are hidden from the user.
The purpose of encapsulation is to separate the user of the object from the designer. The user does not need to know the details of the behavior implementation, but only needs to use the message provided by the designer to access the object.

Package Definition

  1. clear boundaries

All object internal information is bounded within this boundary.

  1. interface

Methods that an object exposes to the outside world through which the outside world can interact with the object.

  1. protected internal implementation

The implementation details of the function, which cannot be accessed from outside the class.

inherit

It means that the new class can obtain the attributes and behaviors of the existing class (called superclass, base class or parent class), and the new class is called the derived class (also called subclass) of the existing class.
In the process of inheritance, the derived class inherits the characteristics of the base class, including methods and instance variables.
Derived classes can also modify inherited methods or add new methods to make them more suitable for special needs.
It helps to solve the problem of software reusability, makes the program structure clear, and reduces the workload of coding and maintenance.

single inheritance

Any one derived class has only a single immediate parent class.
The class hierarchy is a tree structure.

multiple inheritance

A class can have more than one immediate parent.
The class hierarchy is a network structure, and the design and implementation are more complicated.
The Java language only supports single inheritance.

polymorphism

Different methods with the same name coexist in a program.
It is mainly realized by overriding the method of the parent class by the subclass. (Inheritance)
Objects of different classes can respond to messages (methods) with the same name, but the specific implementation methods are different.
The language has the advantages of flexibility, abstraction, behavior sharing, and code sharing, and solves the problem of the same name of the application method well.

int add(int a, int b)     3+5
float add(float a, float b)  3.2 +3.5

class declaration

classes and objects

In a program, an object is described by an abstract data type called a class.
A class is a description of a class of objects. A class is a template for constructing objects.
Objects are concrete instances of classes.

declaration form

	[public] [abstract | final] class 类名称 
  	[extends 父类名称]  
    [implements 接口名称列表]
	{
    
      
		变量成员声明及初始化;
     	方法声明及方法体;
	}

keywords

  1. class

Indicates that what follows is a class.

  1. extends

If the declared class is derived from a parent class, then the name of the parent class should be written after extends.

  1. implements

If the declared class implements certain interfaces, then the name of the interface should be written after implements.

There can be multiple modifiers
, which are used to limit the usage of the class.
public
Indicates that this class is public.
abstract
Indicates that this class is abstract.
final
Indicates that this class is a final class.

Class declaration body
Variable member declaration and initialization

can have multiple

Method declaration and method body

can have multiple

//钟表类
public class  Clock {
    
      // 成员变量
     int hour ;
     int minute ;
     int second ;
     // 成员方法
     public void setTime(int newH, int newM, int newS){
    
     
          hour=newH ;  
           minute=newM ;  
          second=news ;  
     }
     public void showTime() {
    
    
           System.out.println(hour+":"+minute+":"+second);
     }
}

Object declaration and reference

Variables and objects
In addition to storing data of basic data types, variables can also store references to objects. Variables used to store references to objects are called reference variables.
Objects of a class are also called instances of the class.

Object declaration
format
类名 变量名;
For example, Clock is the declared class name, then the variable aclock declared in the following statement will be used to store the reference of this class object:
Clock aclock;
when declaring a reference variable, no object is generated

Object creation
The format of the generated instance:
new <类名>()
for example:
Clock aclock=new Clock()
its role is
to allocate memory space for this object in memory
Return the reference of the object (reference, equivalent to the storage address of the object)
The reference variable can be assigned a null value
For example: aclock=null;
insert image description hereautomatic boxing Unboxing
is a new feature of Java 5, automatic boxing and unboxing of basic data types Before
automatic boxing
Java 5: Integer i = new Integer(2);
Java 5: Integer i = 3; Before
automatic unboxing
Java 5: int j = i.intValue(); //i is an object of type Integer.
Java 5: int j = i; //i is an object of type Integer.

The data member
represents the state of the Java class.
The declared data member must give the variable name and its type, and can also specify other characteristics. The type of the data
member whose member variable name is the only one in a class
can be any data type in Java ( simple type, class, interface, array)
declaration format

		[public | protected | private] 
		[static][ final][transient] [volatile]
		变量数据类型  变量名1[=变量初值], 
			           变量名2[=变量初值],;

format description

public, protected, and private are access control symbols
static indicating that this is a static member variable
final indicating that the value of the variable cannot be modified
transient indicating that the variable is a temporary state
volatile indicating that the variable is a shared variable

Instance Variables
Unmodified staticvariables are called instance variables (Instance Variables),
which are used to store attribute information required by all instances. The attribute values ​​of different instances may be different. The
value of instance attributes can be accessed through the following expressions
<实例名>.<实例变量名>

Object class
Java Object class is the parent class of all classes, that is to say, all classes in Java inherit Object, and subclasses can use all methods of Object.

The Object class is located in the java.lang package and will be automatically imported when compiling. When we create a class, if it does not explicitly inherit a parent class, it will automatically inherit Object and become a subclass of Object.

Object toString()method is used to return a string representation of an object.
Return Value:
Returns a string representation of the object.
Returns object's by default: 类名+@+hashCode的十六类字符串.

Example:
Declare a class representing a circle and save it in the file Circle.java. Then write the test class, save it in the file ShapeTester.java, and Circle.javaput it in the same directory as
see:
JAVA Experiment 2

public class Circle {
    
     
     int radius; 
}
public class ShapeTester {
    
     
    public static void main(String args[]) {
    
     
        Circle x; 
        x = new Circle(); 
             System.out.println(x);  //x.toString()
        System.out.println("radius = " + x.radius); 
    } 
}

After compiling, the running results are as follows:

Circle@26b249
radius =0

Explain
the default toString()return:x.toString()
getClass().getName() + “@” + Integer.toHexString(hashCode())

toString()Is a public method of the Object class, and all classes inherit from the Object class. So even if all classes do not implement the toString method, there will be Objectinheritance from the class toString.

Class variables are also called static variables, and modifiers
are required when declaring them. Regardless of the number of objects in a class, there is only one copy of class variables, and there is only one value in the entire class. The value is assigned when the class is initialized.static

Applicable situations
All objects in the class have the same attributes
Data that often needs to be shared
Some constant values ​​​​used in the system
Reference format
<类名 | 实例名>.<类变量名>

Instance variables
Instance variables are defined in the class without staticmodification in front of them. They are created when an object is created and destroyed when it is destroyed.

Class variables
Class variables are defined in the class and are staticdecorated in front, so they are also called static variables. It is created when the JVM loads the class and executes the static code block in the class. Class variables are common to all objects, and one of the objects changes its value, and the other objects get the changed result.

Example:
For all objects of a circle class, the value of π is required to calculate the area of ​​the circle, and a class attribute PI can be added to the declaration of the Circle class

public class Circle {
    
     
   static double PI = 3.14159265; 
   int radius; 
}

When we generate Circlean instance of a class, the value of PI is not stored in each instance
, and the value of PI is stored in the class

Method members
define the behavior of the class

The things an object can do
The information we can get from an object

There can be none or more; once a method is declared in a class, it becomes part of the class declaration
Divided into instance methods and class methods

声明格式
		[public | protected | private] 
		[static][ final][abstract] [native] [synchronized]
		返回类型  方法名([参数列表]) [throws exceptionList]
		{
    
    
			方法体
		}

format description

The method is modified public, protected, and private to indicate that the method is a class method
for the access control symbol static . The final indicates that the method is a terminal method. The abstract indicates that the method is an abstract method. Native is used to integrate java code and other language codes. Access to Shared Data




Replenish:

Declare the method as final, which means that you already know that the function provided by this method has met your requirements, no extension is required, and any class inherited from this class is not allowed to override this method, but inheritance can still inherit this method , which means it can be used directly. In addition, there is a mechanism called inline, which allows you to directly insert the method body into the call place when calling the final method, instead of performing routine method calls, such as saving breakpoints, pushing the stack, etc., which may cause It improves the efficiency of your program. However, when your method body is very large, or you call this method in multiple places, then your calling body code will expand rapidly, which may affect efficiency instead, so you should use it with caution final for method definition.

Java is not perfect. The shortcomings of Java are reflected in the fact that the running speed is much slower than traditional C++. Java cannot directly access the bottom layer of the operating system (such as system hardware, etc.). For this reason, Java uses native methods to extend Java programs. Function.

The native method can be compared to the interface between a Java program and a C program, and its implementation steps are as follows:

1. Declare the native() method in Java, and then compile;
  2. Use javah to generate a .h file;
  3. Write a .cpp file to implement the native export method, which needs to include the .h file generated in the second step (note that the It also includes the jni.h file with the JDK);
  4. Compile the .cpp file in the third step into a dynamic link library file;
  5. Use the System.loadLibrary() method to load the dynamic link library generated in the fourth step in Java file, the native() method can be accessed in Java.

Method invocation
Sending a message to an object means invoking a method of the object

Obtain information from objects,
modify the state of objects or perform certain operations,
perform calculations and obtain results, etc.

Call format
<对象名>.<方法名>([参数列表])
The <object name> in front of the dot operator "." is called the receiver of the message (receiver)

Parameter passing
Value passing: when the parameter type is a basic data type
Reference passing: when the parameter type is an object type or an array

example;

Circle类中声明计算周长的方法 
public class Circle {
    
     
     static double PI = 3.14159265; 
     int radius;     
		public double circumference() {
    
     
          return 2 * PI * radius; 
     } 
 }

Since radius is an instance variable, Java will automatically take the attribute value of its receiver object when the program is running. You can
also change the body of the circumference method to:
return 2 * PI * this.radius;
the keyword this represents the receiver object of this method

Example method call:

public class CircumferenceTester {
    
     
      public static void main(String args[]) {
    
     
           Circle c1 = new Circle(); 
           c1.radius = 50; 
           Circle c2 = new Circle(); 
           c2.radius = 10;         
	       double circum1 = c1.circumference(); 
           double circum2 = c2.circumference(); 
           System.out.println("Circle 1 has circumference " + circum1); 
           System.out.println("Circle 2 has circumference " + circum2); 
     } 
 }

operation result

Circle 1 has circumference 314.159265
Circle 2 has circumference 62.831853

illustrate

When using an instance method, it needs to be sent to an instance object (also known as sending a message to the object), and the value of radius is the value of the receiver object.

At execution c1.circumference()time, radiusthe value of is the property value c1of radius; at execution c2.circumference()time, radiusthe value of is c2is radiusthe property value of .

Methods with the same method name can be declared in different classes.
When used, the system will find the method of the corresponding class according to the type of the receiver object.

Class method
Also known as 静态方法, it represents the common behavior of objects in the class.
Modifiers are required in front of the declaration . It cannot be declared as staticabstract . Class methods can be directly called with the class name without creating an object, or the static method can be called with a class instance. Can access static members, cannot directly access instance members. Instance methods can access static members as well as instance members. Keywords cannot appear in static methods .




this

Variable-length parameters
Starting from Java 5, variable-length parameters can be used in method parameters.
Variable-length parameters are represented by ellipsis, and their essence is an array.
For example, “String … s”表示“String[] s”
for methods with variable-length parameters, the actual value passed to the variable-length parameters Parameters can be multiple objects, one object or no object.

class organization

Bag

A package
is a collection of classes.
A package can contain several class files and the functions of several
packages
Organize related source code files together
. The space management of class names can be avoided by using packages to divide the name space. Class name conflicts
Provide package-level encapsulation and access rights
Package naming
The name of each package must be "unique".
Package names in Java are represented by lowercase letters

Suggested naming method
Reverse the order of the organization’s Internet domain name as the beginning of the package name.
cn.edu.zzu.www
If there are any characters in the package name that cannot be used as identifiers, replace them with underscores.
If any part of the package name conflicts with keywords, add an underscore
to the package name. Any part of that begins with a digit or other character that cannot be used as the beginning of an identifier, prefixed with an underscore

编译单元与类空间
一个Java源代码文件称为一个编译单元,由三部分组成
所属包的声明(省略,则属于默认包)
import (引入)包的声明,用于导入外部的类
类和接口的声明
一个编译单元中只能有一个public类,该类名与文件名相同,编译单元中的其他类往往是public类的辅助类,经过编译,每个类都会产一个class文件。
利用包来划分名字空间,便可以避免类名冲突。
包的声明
命名的包(Named Packages)
例如: package Mypackage;
默认包(未命名的包)
不含有包声明的编译单元是默认包的一部分

包与目录
Java使用文件系统来存储包和类
包名就是文件夹名,即目录名
目录名并不一定是包名
用javac编译源程序时,如遇到当前目录(包)中没有声明的类,就会以环境变量classpath为相对查找路径,按照包名的结构来查找。因此,要指定搜寻包的路径,需设置环境变量classpath

引入包
为了使用其它包中所提供的类,需要使用import语句引入所需要的类
Java编译器为所有程序自动引入包java.lang
impor语句的格式

  import package1[.package2…]. (classname |*);

其中package1[.package2…]表明包的层次,它对应于文件目录
classname则指明所要引入的类名
如果要引入一个包中的所有类,则可以使用星号(*)来代替类名

类的访问控制

Class access control
There are only two kinds of class access control public(public class) and no modifier (default class).
The relationship between access authority and access capabilities is like
insert image description here
the access control of table class members.

  1. Public (public)
    can be accessed by any other object (provided that there is access to the class where the class member is located)
  2. Protected
    can only be accessed by instance objects of the same class and its subclasses
  3. Private (private)
    can only be accessed by the class itself, not visible outside the class
  4. The default (default)
    only allows access within the same package; also known as "package (package) access rights"

insert image description here
The function of the get method
is to obtain the value of the attribute variable .
getThe method getname begins with the name of the instance variable,
which generally has the following format:

public <fieldType> get<FieldName>() {
    
     
    return <fieldName>; 
}

For the instance variable radius, declare its get method as follows:

public int getRadius(){
    
    
   return radius;
} 

The function of the set method
is to modify the value of the attribute variable .
setThe method setname begins with the name of the instance variable, which
generally has the following format

public void set<FieldName>(<fieldType> <paramName>) {
    
     
    <fieldName> = <paramName>; 
}

The set method for declaring the instance variable radius is as follows:

public void setRadius(int r){
    
    
   radius = r;
}

Use of the keyword this
If the formal parameter name is the same as the instance variable name, you need to add the this keyword before the instance variable name, otherwise the system will treat the instance variable as a formal parameter.
In the above setmethod, if the formal parameter is radius, you need to radiusadd the keyword before the member variable this. code show as below:

public void setRadius(int radius){
    
    
        this.radius = radius;
 }

Object initialization and recycling

Object initialization
When the system generates an object, it will allocate memory space for the object and automatically call the constructor to initialize the instance variables.
Object Recycling
When an object is no longer used, the system will call the garbage collector to reclaim the memory it occupies.

Construction method

Construction method

A special method with the same name as the class
used to initialize the object

Each class in Java has a constructor , which is used to initialize a new object of the class.
For classes that do not define a constructor, the system automatically provides a default constructor

Note: As long as the user declares a constructor, even if no parameterless constructor is declared, the system will no longer assign a default constructor.

Features of the construction method

The method name is the same as the class name
. It has no return type, and the modifier void cannot have it. It is
usually declared as public (public)
and can have any number of parameters.
The main function is to complete the initialization of the object.
It cannot be explicitly called in the program
to generate a object, the system will automatically call the constructor of the class to initialize the newly generated object

Default constructor
The default constructor provided by the system
If no constructor is declared in the class declaration, the Java compiler will provide a default constructor The default constructor
has no parameters, and its method body is empty
Use the default constructor to initialize the object , if no initial value is assigned to the instance variable in the class declaration, the attribute value of the object is zero, empty or false.

Note: As long as the user declares a constructor, even if no parameterless constructor is declared, the system will no longer assign a default constructor.

Example of a default constructor:

//声明一个银行帐号类及测试代码
class BankAccount{
    
    
	String  ownerName;
    int     accountNumber;
    float       balance;
}
public class BankTester{
    
    
     public static void main(String args[]){
    
    		
       BankAccount myAccount = new BankAccount(); 	//调用默认构造方法
       System.out.println("ownerName=" + myAccount.ownerName);
       System.out.println("accountNumber=" + myAccount.accountNumber);
	   System.out.println("balance=" + myAccount.balance);
	}
}

Custom constructor and method overloading
You can pass the initial value to the constructor when generating the object, and use the desired value to initialize the object.
The constructor can be overridden 重载, and the overloading of the constructor is the same as the overloading of the method.
There are two or more methods with the same name but different parameter lists in a class, which is called method overloading. The return value of the method is not included!
When a method is called, Java can distinguish which method should be called by the difference in the parameter list.
Declare a three-parameter constructor for BankAccount

public BankAccount(String initName, int initAccountNumber, float initBalance){
    
     
         ownerName = initName; 
         accountNumber = initAccountNumber; 
         balance = initBalance; 
  }

Assuming that the initial balance of a new account can be 0, you can add a construction method with two parameters

public BankAccount(String initName, int initAccountNumber) {
    
     
        ownerName = initName; 
        accountNumber = initAccountNumber; 
        balance = 0.0f;     
  }

Custom parameterless constructor - impact on subclasses

The no-argument constructor is important for the declaration of its subclasses. If there is no parameterless constructor in a class, the constructor must be declared when the subclass is declared, otherwise an error will occur when the subclass object is initialized.
If the declaration of the subclass construction method does not explicitly call the superclass construction method, the system will automatically call the superclass default construction method (that is, the no-argument construction method) when executing the subclass construction method

Note:
When the user declares a class, if he does not declare any constructor, the system will assign a default (no parameter) constructor to this class.
However, as long as the user declares a constructor, even if no parameterless constructor is declared, the system will no longer assign a default constructor.
Custom constructors without parameters
When declaring constructors, a good declaration habit is

Do not declare a constructor
If declared, declare at least one no-argument constructor

Use of the this keyword
You can use the this keyword to call another constructor in a constructor.
The code is more concise and easier to maintain.
Usually, a constructor with a relatively small number of parameters is used to call a constructor with the largest number of parameters
insert image description here. Example:

public BankAccount(String initName, int initAccountNumber,
 float initBalance) {
    
     
         ownerName = initName; 
         accountNumber = initAccountNumber; 
         balance = initBalance; 
 }
public BankAccount() {
    
     
        this("", 999999, 0.0f);  //调用了上方的构造方法
} 
public BankAccount(String initName, int initAccountNumber) {
    
     
	  this(initName, initAccountNumber, 0.0f);    //调用第一个构造方法
}

memory reclamation technology

Memory recovery technology
When an object is no longer used in the program, it becomes a useless object

The current code segment does not belong to the scope of the object.
Assign the reference of the object to null

The Java runtime system periodically releases the memory used by useless objects through the garbage collector. The Java runtime system will automatically call the method
of the object before automatic garbage collection of the object.finalize()

Garbage collector
Automatically scans the dynamic memory area of ​​objects and marks unused objects for garbage collection
Runs as a thread

Usually executed asynchronously when the system is idle Runs synchronously with
the system when the system runs out of memory or calls in the program require System.gc()garbage collection

finalize()The method
is declared in the class java.lang.Object, so every class in Java has this method
. It is used to release system resources, such as closing open files or socket(sockets), etc.
Declaration format

protected void finalize() throws throwable

finalize()If a class needs to release resources other than memory, it needs to override the method in the class

Memory overflow : ( out of memory) The common understanding is that there is not enough memory. Usually when running large-scale software or games, the memory required by the software or games far exceeds the capacity of the memory installed in your host, which is called memory overflow. For example, if you apply for an int, but save the number that can only be stored in a long, that is a memory overflow.
Memory leak : ( Memory Leak) refers to the heap memory that has been dynamically allocated in the program is not released or cannot be released for some reason, resulting in a waste of system memory, resulting in serious consequences such as slowing down the running speed of the program and even system crashes. The harm of a memory leak can be ignored, but the consequences of memory leak accumulation are very serious. No matter how much memory is used, it will be used up sooner or later.

Memory leak ==== "Memory overflow

pointer hanging

A dangling pointer refers to a pointer pointing to a piece of memory that is not allocated to the user.

  1. 指针未初始化
    This isn't just a beginner's mistake. Especially for global pointer variables, it is normal to use them without initialization. Consider the following code:
    insert image description here
    insert image description here
  2. 指针拷贝后删除了指针
    insert image description here

insert image description here
insert image description here
insert image description here

Application examples

enumerated type

When a finite collection is required, and the data in the collection is a specific value, the enumeration type
format can be used:

[public] enum 枚举类型名称 [implements 接口名称列表]
{
    
      
     枚举值;
     变量成员声明及初始化;
     方法声明及方法体;
} 

Example:

 enum Score {
    
    
         EXCELLENT,
         QUALIFIED,
         FAILED;
  };
public class ScoreTester {
    
    
         public static void main(String[] args) {
    
    
                 giveScore(Score.EXCELLENT);
         }
        public static void giveScore(Score s){
    
    
             switch(s){
    
    
                 case EXCELLENT:
                     System.out.println("Excellent");
                     break;
                 case QUALIFIED:
                     System.out.println("Qualified");
                     break;
                 case FAILED:
                     System.out.println("Failed");
                     break;
             }
         }
     }

toString method

public String toString() Method
is the method of Object, which converts the content of the object into a string

All Java classes have a default toString() method whose body is as follows:

 getClass().getName() + '@' Integer.toHexString(hashCode())

public static String toHexString(int i)
A static method under the Integer class converts an integer into a string represented in hexadecimal.
public native int hashCode()
By default, Object in hashCode() returns the 32-bit jvm memory address of the object.

The following two lines of code are equivalent

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

If you need a special conversion function, you need to override the toString() method yourself

public String toString() A few points about the method
toString() method
must be declared as public
the return type is String
the name of the method must be toStringand has no parameters
do not use the output method in the method bodySystem.out.println()

Add your own toString() method to the BankAccount class

insert image description here

java.text.DecimalFormat类

DecimalFormatNumberFormat 的子类,用于格式化十进制数字。
//默认的方言和格式化模板
DecimalFormat defaultFormat = new DecimalFormat();
//指定格式化模板,默认方言
DecimalFormat patternFormat = new DecimalFormat("0");
//指定中国方言和格式化模板
DecimalFormat decimalFormat = new DecimalFormat("0",new DecimalFormatSymbols(Locale.CHINA));
String pattern = "0";//指定格式化模式
defaultFormat.applyPattern(pattern);//应用格式化模式

java.text.DecimalFormat//指定格式化模式
String pattern = "0";
//应用格式化模式
defaultFormat.applyPattern(pattern);
DecimalFormat 类主要靠 # 和 0 两种占位符号来指定数字长度。
0 表示如果位数不足则以 0 填充。如果number的位数大于等于pattern的0的个数,result=number。
# 否则不够的位数以0填充。
# 表示数字,如果是0则不显示(仅限开始和小数点后的末尾位置)

DecimalFormatClass
instance methods format()to format data

public String format(int/float/double number)

insert image description here
The modified toString() method is as follows

public String toString() {
    
     
    return("Account #" + accountNumber + " with balance " +
     new java.text.DecimalFormat("$0.00").format(balance)); 
}

Override (Override/Overriding) means that the subclass rewrites the implementation process of the methods allowed to be accessed by the parent class, and the return value and formal parameters cannot be changed. That is, the shell remains unchanged, but the core is rewritten! The advantage of rewriting is that subclasses can define their own specific behavior according to their needs. That is to say, the subclass can implement the method of the parent class as needed.
Overloading (overloading) is in a class, the method name is the same, but the parameters are different. The return types can be the same or different. Each overloaded method (or constructor) must have a unique list of parameter types.

In java, if @Overridethe annotation is added to the method, it means that the subclass rewrites the method of the parent class. Of course, you can also not write, the advantage of writing is:

Improved readability
The compiler will check whether the written method exists in the parent class

insert image description here

Three, the method in the class

exception handling

An exception exceptionis a problem that prevents the current program or method from continuing to execute.

If used System.out.println(11/0), an exception will be thrown because 0 is used as the divisor java.lang.ArithmeticException.

There are many reasons for exceptions, usually including the following categories:

  1. The user entered illegal data.
  2. The file to open does not exist.
  3. The connection is interrupted during network communication, or the JVM memory overflows.
    Some of these exceptions are caused by user errors , some by program errors , and others by physical errors .

Java exceptions are divided into two types:

  1. RuntimeException (RuntimeException), unchecked exception.
  2. Non-runtime exception (CheckedException), checked exception.

Unchecked exceptions (runtime exception unchecked exceptions):

This kind of exception does not need to be caught, and the programmer can not handle it. When an exception occurs, the virtual machine will handle it.

NullPointerException (null pointer exception),
IndexOutOfBoundsException (subscript out-of-bounds exception)
ClassCastException (class conversion exception)
ArrayStoreException (data storage exception, inconsistent types when operating arrays)
BufferOverflowException exception for IO operations

Checked exceptions (non-runtime abnormal checked exceptions):

This kind of abnormal user program must be caught and processed, otherwise the compilation will fail. The java compiler requires programmers to catch this kind of exception. Java believes that checked exceptions are exceptions that can be handled (repaired), so Java programs must explicitly Handle checked exceptions.

IOException
SQLException
User-defined Exception
When writing code, a red line appears, and try catch or throws are required to handle the exception.

error error :

Errors are not exceptions, but errors that the program cannot handle, indicating a serious problem in running the application. Most errors are not related to actions performed by the code writer, but represent problems with the JVM (Java Virtual Machine) when the code is running. For example, 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.
error indicates a serious problem where recovery is not impossible but difficult. For example, memory overflow.
error means a serious problem that the application program itself cannot overcome and recover from, and the program can only die.

What is the difference between error and exception? [Basic]

Answer: errorIndicates system-level errors and exceptions that the program does not have to handle; such as memory overflow, it is impossible to expect the program to handle such situations; the Error class object is generated and thrown by the Java virtual machine, and most errors are related to the execution of the code writer Operation is irrelevant. 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. In Java, errors are usually described using subclasses of Error.

exceptionIndicates an exception that needs to be caught or needs to be handled by the program, and is a design or implementation problem; that is, it indicates a situation that would never occur if the program was functioning normally. Exception is further divided into checked exceptions and unchecked exceptions.
Checked exceptions must be explicitly caught in the source code as part of compile-time checking.
Unchecked exceptions refer to runtime exceptions, such as NullPointerException, ArrayIndexOutOfBoundsException, etc., which are usually logic errors that can be avoided by coding. It is determined according to the needs whether they need to be caught or not, and will not be mandatory at compile time.

insert image description hereFor checked exceptions, Java forces the program to handle them. There are two processing methods:
Catch exception
Use try{}catch(){} block to capture the exception that occurs and handle it accordingly.
Declaring throwing exceptions
does not handle exceptions in the current method, but throws exceptions to the calling method.
For unchecked exceptions

Catch the exception:

//语法格式
try {
    
    
      statement(s)
} catch (exceptiontype name) {
    
    
     statement(s)
} catch (exceptiontype name) {
    
    
     statement(s)
}
………
finally {
    
    
     statement(s)
}

Explanation:
try The statement
is followed by a code block
catchstatement that may generate an exception
, followed by an exception handling statement, usually using two methods
getMessage() – returning a string to describe the exception that occurred.
printStackTrace()– Give the calling sequence of the method until the
finallystatement where the exception occurs. Regardless of whether an exception occurs
in the code segment, the following program code segment will be executed. Usually other resources other than memory are released heretryfinally

What is the difference between final, finally, and finalize? [Basic]
Answer: final: Modifier (keyword); if a class is declared final, it means that it can no longer derive new subclasses and cannot be inherited as a parent class, so a A class cannot be declared as both abstract and final; declaring variables or methods as final can ensure that they will not be changed during use; variables declared as final must be given an initial value at the time of declaration, and It can only be read in future references and cannot be modified; the method declared as final can also only be used and cannot be overloaded.
finally: Provide a finally block to perform any cleanup operations during exception handling ; regardless of whether an exception is generated in the try code segment, the program code segment after finally will be executed.
finalize: Method name; Java technology allows the use of finalize() methods to do the necessary cleanup before the garbage collector clears the object from memory. This method is called by the garbage collector on this object when it determines that this object is not being referenced. It is defined in the Object class, so all classes inherit from it. Subclasses override the finalize() method to organize system resources or perform other cleanup tasks. The finalize() method is called on an object before it is deleted by the garbage collector.

Catch exceptions of type NumberFormatException

insert image description hereCatch division by zero exceptions (exceptions of type ArithmeticException)

insert image description hereImprove the program: Repeat the prompt for input until legal data is entered. In order to avoid code duplication, data can be stored in an array

insert image description here
Declare throwing exceptions
If the programmer does not want to handle exceptions in the current method, he can use throwsclause declarations to throw exceptions into the calling method.
If all the methods choose to throw this exception, it JVMwill , the relevant error message will be output, and the running of the program will be terminated. During the exception being thrown, any method can catch it and handle it accordingly.

The difference between throws and throw
throws appears in the method declaration, indicating that the method may throw exceptions, allowing throwsmultiple exception types
throwto appear in the method body to throw exceptions. When the method encounters an exception during execution, the exception information is encapsulated as an exception object, and then throw.

insert image description hereIf a FileNotfoundException is thrown in openThisFile, getCustomerInfo will stop executing and pass the exception to its caller

public void openThisFile(String fileName) 
     throws java.io.FileNotFoundException {
    
           //code  for method 
 }

public void getCustomerInfo() 
    throws java.io.FileNotFoundException {
    
             
    // do something        this.openThisFile("customer.txt");        
     // do something  }

If an exception occurs inside the function method and the program cannot continue to run, use throw to throw the exception object.
Format: throw new xxxException("异常产生的原因");
If throw throws a runtime exception or its subclasses, no exception handling is required, if not, exception handling is also required ( try-catchor throws).

insert image description here
Declare your own exception class
In addition to using the system predefined exception class, users can also declare their own exception class.
All custom exception classes must be Exceptionsubclasses of .
The general declaration method is as follows

public class MyExceptionName extends SuperclassOfMyException {
    
     
       public MyExceptionName() {
    
     
             super("Some string explaining the exception"); 
        } 
} 

Declares the exception class thrown when the divisor is zeroDivideByZeroException
insert image description here

superIt can be understood as a pointer to the nearest parent class object
super.xxxto refer to the members of the parent class, including variables and methods.
super(参数): Call a constructor in the parent class (should be the first statement in the constructor).
this.xxxTo refer to members of this class, including variables and methods.
this(参数): Call another form of constructor in this class (should be the first statement in the constructor).

insert image description here
throwStatement syntax: used in the method body
throw newto construct the method name (parameter list) of the exception class;
for example:
throw new Exception("除数为零无意义");
use throwsthe clause to throw an exception in the method, and use it in the method declaration.
The format is as follows:

返回类型 方法名(可选参数表) throws 异常类名{
    
    
      自动或主动引发异常的方法体代码
}

Errors and Assertions

assert(assert) statement: A statement that asserts arbitrarily, such as asserting that a condition must be true.

The old man pointed at the watermelon: This is a watermelon, the assertion is true.
The old man pointed to the watermelon: My watermelon is the No.1 sweet in the world. The assertion does not hold.

There are two syntaxes:

assert 条件表达式
assert 条件表达式 : 字符串型断言消息

Virtual machines always have assertions turned off by default. Assertion statements are suitable for program debugging and troubleshooting.
An assertion error was encountered, and the program terminated abnormally if the virtual machine was in an assertion-enabled state

Allows assertion command format:

java  -ea  主类名

Example:

import java.util.*;
public class ch31 {
    
    
    public static void main(String[] args) {
    
    
        try {
    
    
            Scanner input = new Scanner(System.in);
            System.out.println("请输入要计算平方根的数");
            double x = input.nextDouble();
            //assert x > 0 : "负数不能计算平方根";
            double sqr = Math.sqrt(x);
            System.out.printf("平方根:%.4f", sqr);
        } catch (Exception e) {
    
    
            System.out.println("能运行到这里吗?");
            System.out.println("异常" + e.getMessage());
        }
    }
}

Run the following without assertions:
insert image description here

IDEA does not enable assertion by default (even if the assertion is written, it is useless)
now enable assertion

insert image description here

insert image description here
Fill in the vm option-ea

Re-ran and found that the assertion was triggered.
insert image description here


Summarize:

  1. The exception is that something unexpected happened during the operation, and it cannot continue to run as usual. Use a try-catch-finally block to catch and handle exceptions.
  2. Code blocks that capture and handle exceptions can also be nested to meet complex requirements.
  3. All exception classes form a tree-like hierarchy, and the topmost exception class is Exception.
  4. Exceptions can be actively and precisely thrown using the throw statement. You can also kick the exception that occurs in the method to the method that calls it for processing. In this case, use the throws clause in the method header.
  5. In addition to exceptions, there are Errors. Errors are more serious than exceptions and cannot be caught and handled in the program. For example, assertion errors, errors in the virtual machine itself, and so on.
  6. In the assertion statement, if the assertion condition is not established, an assertion error occurs, and the program has to be interrupted by itself. Assertion statements are not executed by default, and assertions are generally only enabled during program debugging.

method overloading

method overloading

Multiple methods with the same name in a class
The parameters of these methods must be different, and Java can identify overloaded methods by different parameter lists

参数个数不同  或	 参数类型不同

The return values ​​can be the same or different
The value of overloading is that it allows multiple methods to be accessed by using one method name

example:

//通过方法重载分别接收一个或几个不同数据类型的数据

class MethodOverloading {
    
    
    public void receive(int i){
    
    
        System.out.println("Receive one int parameter. ");
        System.out.println("i="+i);
    }
    public void receive(double d){
    
    
        System.out.println("Receive one double parameter. ");
        System.out.println("d="+d);
    }
    public void receive(String s){
    
    
        System.out.println("Receive one String parameter. ");
        System.out.println("s="+s);
    }
    public void receive(int i,int j){
    
    
        System.out.println("Receive two int parameters. ");
        System.out.println("i=" + i + "  j=" + j);
    }
    public void receive(int i,double d){
    
    
        System.out.println("Receive one int parameter and one double parameter. ");
        System.out.println("i=" + i + "  d=" + d);
    }
}
public class c32 {
    
    
    public static void main(String args[]){
    
    
        MethodOverloading m = new MethodOverloading();
        m.receive(2);
        m.receive(5.6);
        m.receive(3,4);
        m.receive(7,8.2);
        m.receive("Is it fun?");
    }
}

Run to get:

insert image description here

Execute the script in the method

Java 6's new feature,
Java's scripting API, provides a framework independent of various scripting languages, which can be used to execute scripts in Java code.
Through the scripting API, programmers can use Java to write customizable and extensible applications, and leave the parts that need to be customized and extended to others to implement using scripts.
Java's scripting API is located javax.scriptin the package, and the ScriptEngineManager class in this package can obtain the scripting engine.

Simply put, a script is a series of text commands, which can be seen (for example, you can use Notepad to open, view and edit). Translate into machine-recognizable instructions and execute them in sequence. Because the script has an additional translation process during execution, its execution efficiency is slightly lower than that of binary programs.

Batch files , also known as batch scripts. As the name implies, batch processing is to perform batch processing on an object, and is generally considered to be a simplified scripting language, which is applied to DOS and Windows systems. On DOS and Windows (any) systems, a .bat file is an executable file consisting of a sequence of commands, which may contain calls to other programs.

Shell is a program written in C language, which is a bridge for users to use Linux. Shell is both a command language and a programming language.

Shell, commonly known as the shell (used to distinguish it from the core), refers to the software (command interpreter, command parser) that "provides the user with an operation interface". It is similar to COMMAND.COM and later cmd.exe under DOS. It receives user commands and then invokes the corresponding application.

Shell refers to an application program that provides an interface through which users access the services of the operating system kernel.

Ken Thompson's sh is the first Unix shell, and Windows Explorer is a typical graphical interface shell.

Shell script (shell script) is a script program written for the shell.
The shell mentioned in the industry usually refers to the shell script, and the shell and the shell script are two different concepts.

Execute the script in the method

The simplest process to execute a script is as follows:

1.创建一个ScriptEngineManager对象;
2.通过ScriptEngineManager对象获得一个ScriptObject对象;
3.通过ScriptObject对象的eval方法执行脚本。 

Fourth, the reuse of classes, generics, and basic classes

class inheritance

A mechanism for creating new classes from existing classes, one of the cornerstones of object-oriented programming.
Through inheritance , new classes can be defined based on existing classes, and new classes have all the functions of existing classes

Java only supports single inheritance of classes , and each subclass can only have one direct parent class. The parent class is a collection of public attributes and methods
of all subclasses , and the subclass is the special inheritance mechanism of the parent class, which can improve the abstraction of the program. Improve code reusability

The base class (base class),
also known as 超类(superclass), 父类
is a class that is directly or indirectly inherited

A derived class (derived-class)
is also called 子类 (subclass)
a class obtained by inheriting other classes.
It inherits the state and behavior of all ancestors.
The derived class can add variables and methods.
The derived class can also 覆盖/重写(override)inherit the method.

The concept of inheritance - is_a relationship

The relationship between subclass objects and parent class objects exists “IS A”(or "is a kind of")

insert image description here

Take the animal level as an example:
insert image description here

The concept of inheritance - derived class object

Objects produced
by derived classes Externally, it should contain

  1. same interface as base class
  2. Can have more methods and data members

It contains a subobject of the base class type

Inherited syntax:

class childClass extends parentClass
{
    
     
	         //类体
}

for example:

In a company , there are two types of employees :
employees and managers In addition to the attributes of ordinary employees, managers (Managers) may also have the following attributes Responsibilities (responsibilities) Managed employees (listOfEmployees)






Class diagram of Employee and Manager

insert image description here

//父类Employee
    class Employee
    {
    
    
        int  employeeNumbe ;
        String  name, address, phoneNumber ;
    }
    //子类Manager
    class  Manager extends Employee
    {
    
    
        //子类增加的数据成员
        String responsibilities, listOfEmployees;
    }

Example:
There are three classes: Person, Employee, Manager
insert image description here

package c4;
class person{
    
    
    public String name;
    public String getName(){
    
    
        return name;
    }
}
class Employee extends person{
    
    
    public int employeeNumber;
    public int getEmployeeNumber(){
    
    
        return employeeNumber;
    }
}

class Manager extends Employee{
    
    
    public String responsibilities;
    public String getResponsibilities(){
    
    
        return responsibilities;
    }
}

public class c41 {
    
    
    public static void main(String args[]){
    
    
        Employee zhang = new Employee();
        zhang.name = "张三";
        zhang.employeeNumber = 20220606;
        System.out.println(zhang.getName());
        System.out.println(zhang.getEmployeeNumber());

        Manager li = new Manager();
        li.name = "李四";
        li.employeeNumber = 20200505;
        li.responsibilities = "Internet project";
        System.out.println(li.getName());;
        System.out.println(li.getEmployeeNumber());
        System.out.println(li.getResponsibilities());
    }
}

insert image description here

Subclasses cannot directly access private properties and methods inherited from parent classes, but can use public (and protected) methods for access

public class B {
    
     
      public int a = 10; 
      private int b = 20; 
      protected int c = 30; 
      public int getB()  {
    
     return b; } 
} 
public class A extends B {
    
     
      public int d; 
      public void tryVariables() {
    
     
           System.out.println(a);             //允许 
           System.out.println(b);             //不允许
           System.out.println(getB());        //允许 
           System.out.println(c);             //允许 
      } 
}

Hiding and overriding/overriding

hide

Subclasses can redefine the attribute variables and methods inherited from the parent class.
Overriding is the subclass rewrites the implementation process of the access-allowed methods of the parent class, and neither the method name nor the formal parameters can be changed . That is, the shell remains unchanged, but the core is rewritten!

The advantage of rewriting is that subclasses can define their own specific behavior according to their needs. That is to say, the subclass can implement the method of the parent class as needed.

insert image description here
How to access the hidden parent class attribute
Call the method inherited from the parent class, then the operation is the attribute inherited from the parent class
Use super.the attribute superto represent the reference of the parent class object

for example:

package c4;
class A1{
    
    
    int x = 2;
    public void setX(int i) {
    
    
        x = i;
    }
    void printa()
    {
    
    
        System.out.println("A.x="+x);
    }

}

class B1 extends A1{
    
    
    int x = 100;
    void printb(){
    
    
        super.x = super.x + 10;
        System.out.println("super.x="+super.x+" B.x="+x);
    }
}
public class c42 {
    
    
    public static void main(String []args){
    
    
        A1 a1 = new A1();
        a1.printa();
        a1.setX(4);
        a1.printa();

        B1 b1 = new B1();
        b1.printb();
        b1.printa();

        b1.setX(5);
        b1.printb();
        b1.printa();
        b1.printa();

    }
}

insert image description here
Subclasses cannot inherit the static properties of the parent class, but can operate on the static properties of the parent class.
For example, in the above example, int x = 2;change to static int x = 2;, and then compile and run the program, the following results will be obtained:

insert image description here

method override

Method coverage
Subclass rewrites the implementation process of the access-allowed method of the parent class. The method name and
number of parameters of the method coverage method must be exactly the same as the method being covered.
Only when the return value is a class type, the overridden method can modify the return value type, and must be a subclass of the return value of the parent method.
Simply use the object name of a different class in front of the method name to distinguish the overriding method from the overridden method.
The access rights of the overriding method may be looser than the overridden one, but not more restrictive.
Member methods of a superclass can only be overridden by its subclasses .
A subclass method cannot throw more compile-time exceptions ( 检查型异常, 非运行异常) than a superclass method.

Methods that must be overridden
The derived class must override the abstract method in the base class, otherwise the derived class itself becomes a
method that cannot be overridden by the abstract class

基类中声明为`final`的终结方法
基类中声明为`static` 的静态方法
构造方法

call the overridden method
super.overriddenMethodName();

Application occasions of method overriding
The subclass implements the same function as the parent class, but uses different algorithms or formulas
In the method with the same name, more things need to be done than the parent class
In the subclass, it is necessary to cancel the inheritance from the parent class method

constructor with inheritance

The construction method when there is inheritance follows the following principles

  1. Subclasses cannot inherit constructors from parent classes
  2. In the construction method of the subclass, the construction method of the parent class is called, and the calling statement must appear in the first line of the construction method of the subclass, and the super keyword can be used
  3. If the declaration of the subclass construction method does not explicitly call the superclass construction method, the system will automatically call the superclass default construction method (that is, the no-argument construction method) when executing the subclass construction method
  4. By default, the first line of the subclass construction method is: super(), which can exist without writing.

insert image description here
This and super compare
this: represents the reference of this class object
super: represents the reference of the parent class object

Notes on using this(…) and super(…):
Subclasses use this(…) to call other construction methods of this class.
Note: this(…) super(…) can only be placed in the first line of the constructor.

Object class

The Object class is
the direct or indirect parent class of all classes in the Java program, the parent class of all classes in the class library, and is at the top level of the class.
Contains the public properties of all Java classes.

ObjectThe class defines the states and behaviors that all objects must have. The main methods are as follows

public final Class getClass()  
获取当前对象所属的类信息,返回Class对象
public String toString() 
返回当前对象本身的有关信息,按字符串对象返回
public boolean equals(Object obj)  
比较两个对象是否是同一对象,或者对象是否相等(重写)
protected Object clone( )  
生成当前对象的一个拷贝,并返回这个复制对象
public native int hashCode()   
返回该对象的哈希码值
protected void finalize() throws Throwable 
定义回收当前对象时所需完成的资源释放工作

Object class (continued)—hashCode()

public native int hashCode()

  1. By default, the 32-bit jvm memory address of the returned object is a hash code of type int . The hash code of the object is to better support the Java collection classes based on the hash mechanism , such as Hashtable, HashMap, HashSet, etc.
  2. nativeFor local methods, the specific implementation may be different in different environments, and the obtained hash codes may not necessarily be the same, and are usually related to the address of the object.
  3. nativeIndicates that this method needs to use methods written in other languages ​​to realize its functions. A native method is an interface for Java to call non-Java code. The implementation of the method is implemented by a non-Java language, such as C or C++.

What is a hash table? How to implement hash lookup?
哈希表(Hash table, also called hash table), is a data structure that is directly accessed according to the key value (Key value). It accesses records by mapping the key value Key to a location in the table to speed up lookups. This mapping function is called a hash function, and the array storing the records is called a hash table.
Given a table M, there is a function f(key). For any given key value key, if the address of the record in the table containing the key can be obtained after substituting the function, the table M is called a hash (Hash). table, the function f(key) is a hash (Hash) function.

Hash

Hash, generally translated as hash, hash, or transliterated as hash, is to transform an input of any length into a fixed-length output through a hash algorithm, and the output is the hash value.
This transformation is a compression map, that is, the space of the hash value is usually much smaller than the space of the input.
Different inputs may hash to the same output, so it is impossible to determine a unique input value from the hash value.
The Hash algorithm is also called a hash algorithm. Although the Hash algorithm is called an algorithm, it is actually more like an idea. The Hash algorithm does not have a fixed formula, as long as the algorithm conforms to the hash idea, it can be called a Hash algorithm.
insert image description here
insert image description hereThe principle of hashing technology-remainder method/modulo operation
insert image description here

Hash algorithm: use "modulo operation" calculation to obtain the storage location.
Advantages: Quickly hit the target of the search

Object class (continued)—toString()

public String toString()
Return information about the current object itself, returned as a string object.

public String toString() {
    
    
        return getClass().getName() + "@" +   
                         Integer.toHexString(hashCode());
}

hashCode()It is an address corresponding to an object in the heap.
public static String toHexString(int i)
IntegerA static method under the class converts an integer into a string represented by hexadecimal.

Example: automatic calltoString()

package c4;

public class ObjectToString {
    
    
    public static void main(String args[]) {
    
    
        ObjectToString ots=new ObjectToString();
        System.out.println("ots is:"+ots);
        System.out.println("ots's toString is:"+ots.toString());
    }
}

insert image description here

Object class—equal and identical (equal & ==)

The concept of equality and identity
Two objects with the same type and the same attribute values ​​are said to be equal (equal).
Two reference variables (objects) are said to be identical if they point to the same object.
Two objects that are identical must be equal.
Two objects are equal, not necessarily identical.
The comparison operator "==" judges whether the two objects are the same.

== , if applied to a variable of a basic data type, directly compare whether the stored "value" is equal.
If applied to a variable of a reference type, compare the address of the pointed object. == Determines whether the addresses of two objects are equal. That is, to determine whether two objects are the same object

public boolean equals(Object obj)
All Java classes inherit equals()methods.
The equals() method of the Object class is defined as follows. It can be seen that it also judges whether two objects are the same.

public boolean equals(Object x) {
    
     
        return this == x; 
}

Rewriting of the equals method
To judge whether the values ​​of each property field of two objects are the same, the equals method inherited from the Object class cannot be used, but the equals method needs to be rewritten in the class declaration.
The equals method of the Object class has been rewritten in the String class to determine whether two strings have the same content.

Add the equals method in the BankAccount class. Since the equals method in the Object class is rewritten, the method definition header must be exactly the same as the equals method in the Object class.
insert image description here

Experiment example:

Write a Person class. By rewriting the toString(), equals(), and hashcode() methods, the comparison between equals and == can be performed on the objects instantiated from the Person class.

package test5;

import java.util.Objects;

class person {
    
    
    String sex;
    int age;
    String name;
    boolean notempty;
    public person(String sex,int age,String name){
    
    
        this.sex = sex;
        this.age = age;
        this.name = name;
        this.notempty = true;
    }

    @Override
    public String toString() {
    
    
        return "person{" +
                "sex='" + sex + '\'' +
                ", age=" + age +
                ", name='" + name + '\'' +
                '}';
    }

    @Override
    public boolean equals(Object o) {
    
    
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        person person = (person) o;
        return age == person.age && sex.equals(person.sex) && name.equals(person.name);
    }

    @Override
    public int hashCode() {
    
    
        return Objects.hash(sex, age, name);
    }

    public static void main(String args[]){
    
    
        person p1 = new person("男",20,"张三");
        person p2 = new person("男",20,"张三");
        System.out.println("p1 is " + p1 );
        System.out.println("p2 is " + p2 );
        System.out.println(p1.hashCode() == p2.hashCode());
        System.out.println(p1 == p2);
        System.out.println(p1.equals(p2));
    }
}

insert image description here

Object clone( )

Note: I learned this knowledge point according to the teacher's ppt. After finishing it, I feel that the teacher's thinking is relatively convoluted, and I skipped some basic knowledge. It is recommended to read the following reference blog first.

Reference blog:
https://www.cnblogs.com/ysocean/p/8482979.html

Clone is a method in the Object class. Through the object A.clone() method, an object B with the same content as the object A will be created. Clone clone, as the name implies, is to create an object that is exactly the same.

  Person p4 = (Person) p3.clone();

The clone method
implements the interface for the cloned class Cloneable, and rewrites the clone method of the Object class, which is divided into deep and shallow methods.
To clone an object 深拷贝, in addition to calling the clone method in the parent class to obtain a new object, the reference variable in the class must also be cloned.
If you just use the default clone method in Object, yes 浅拷贝.

The clone provided by the Object class can only implement a shallow copy.

protected Object clone( )
Constructing a new object based on an existing object
is defined in the root class Object protected, so it needs to be overridden as public
the class is cloned, and Cloneablethe interface must be implemented to give the class the ability to be cloned

class MyObject implements Cloneable 
{
    
      
    //…
}

1. Why copy

希望生成一个和原来一样的对象,对这个对象的修改不改变原对象的属性值(深拷贝)。

2. The difference between deep copy and shallow copy

浅拷贝对基本数据类型生成一份新的拷贝;
  对引用类型,只是复制了引用,引用所指向的内存空间并没有拷贝。
深拷贝除了复制引用,对引用指向的内存空间也进行拷贝(新内存空间)。
  深拷贝把复制对象所引用的对象也进行了拷贝。Line类(属性:Point p1,p2)

Analyze through two project examples;

Example of a shallow copy project:
insert image description here

BirthDate.javadocument

package c4.qiankaobei;
public class BirthDate {
    
    
    private int year;
    private int month;
    private int day;
    public int getYear() {
    
    
        return year;
    }
    public void setYear(int year) {
    
    
        this.year = year;
    }
    public int getMonth() {
    
    
        return month;
    }
    public void setMonth(int month) {
    
    
        this.month = month;
    }
    public int getDay() {
    
    
        return day;
    }
    public void setDay(int day) {
    
    
        this.day = day;
    }
    public BirthDate() {
    
    
    }
    public BirthDate(int year, int month, int day) {
    
    
        this.year = year;
        this.month = month;
        this.day = day;
    }
    @Override
    public String toString() {
    
    
        return "BirthDate [year=" + year + ", month="
                + month + ", day=" + day + "]";
    }
}

Student.java

package c4.qiankaobei;
public class StudentQianClone implements Cloneable{
    
    
    private int stuNo;
    private String name;
    private BirthDate birthday;
    public int getStuNo() {
    
    
        return stuNo;
    }
    public void setStuNo(int stuNo) {
    
    
        this.stuNo = stuNo;
    }
    public String getName() {
    
    
        return name;
    }
    public void setName(String name) {
    
    
        this.name = name;
    }
    public BirthDate getBirthday() {
    
    
        return birthday;
    }
    public void setBirthday(BirthDate birthday) {
    
    
        this.birthday = new BirthDate(); //深复制
        this.birthday.setYear(birthday.getYear());
        this.birthday.setMonth(birthday.getMonth());
        this.birthday.setDay(birthday.getDay());
    }
    public StudentQianClone() {
    
    
    }
    public StudentQianClone(int stuNo, String name, BirthDate birthday) {
    
    
        this.stuNo = stuNo;
        this.name = name;
        this.birthday = birthday;
    }
    @Override
    protected Object clone() throws CloneNotSupportedException{
    
    
        return (StudentQianClone) super.clone();
    }
}

package c4.qiankaobei;
public class CopyStudentQianClone {
    
    
    public static void main(String[] args) throws CloneNotSupportedException {
    
    
        BirthDate birthday= new BirthDate(2000,1,1);
        StudentQianClone s1 = new StudentQianClone(202201,"张三", birthday);
        System.out.println(s1.getStuNo());
        System.out.println(s1.getName());
        System.out.println(s1.getBirthday());
        StudentQianClone s2 = (StudentQianClone) s1.clone();
        System.out.println(s1.getStuNo());
        System.out.println(s1.getName());
        System.out.println(s1.getBirthday());
        System.out.println("s2==s1:"+ (s2==s1));
        System.out.println("s2.birthday==s1.birthday:"+
                (s2.getBirthday()==s1.getBirthday()));
    }
}

Run the screenshot:
insert image description here

Here we can see that the information of s2 and s1 is exactly the same, but s2 and s1 are not 同一, not an object.
But the birthday of s1 and the birthday of s2 are 同一yes.

insert image description hereThe above is a shallow copy,

Deep copy also copies the memory space pointed to by the reference (new memory space). A deep copy will also copy all the objects referenced by the copied object.

insert image description hereExample of a deep copy project
insert image description here
The project structure is as follows:
BirthDateShenClone.java

package c4.shenclone;
public class BirthDateShenClone implements Cloneable{
    
    
    private int year;
    private int month;
    private int day;
    public int getYear() {
    
    
        return year;
    }
    public void setYear(int year) {
    
    
        this.year = year;
    }
    public int getMonth() {
    
    
        return month;
    }
    public void setMonth(int month) {
    
    
        this.month = month;
    }
    public int getDay() {
    
    
        return day;
    }
    public void setDay(int day) {
    
    
        this.day = day;
    }
    public BirthDateShenClone() {
    
    
    }
    public BirthDateShenClone(int year, int month, int day) {
    
    
        this.year = year;
        this.month = month;
        this.day = day;
    }
    @Override
    public String toString() {
    
    
        return "BirthDate [year=" + year + ", month="
                + month + ", day=" + day + "]";
    }
    @Override
    protected Object clone() throws CloneNotSupportedException {
    
    
        // TODO Auto-generated method stub
        return (BirthDateShenClone)super.clone();
    }
}

StudentShenClone.java

package c4.shenclone;

public class StudentShenClone implements Cloneable {
    
    
    private int stuNo;
    private String name;
    private BirthDateShenClone birthday;
    public int getStuNo() {
    
    
        return stuNo;
    }
    public void setStuNo(int stuNo) {
    
    
        this.stuNo = stuNo;
    }
    public String getName() {
    
    
        return name;
    }
    public void setName(String name) {
    
    
        this.name = name;
    }
    public BirthDateShenClone getBirthday() {
    
    
        return birthday;
    }
    public void setBirthday(BirthDateShenClone birthday) {
    
    
        this.birthday = new BirthDateShenClone(); //深复制
        this.birthday.setYear(birthday.getYear());
        this.birthday.setMonth(birthday.getMonth());
        this.birthday.setDay(birthday.getDay());
    }
    public StudentShenClone() {
    
    
    }
    public StudentShenClone(int stuNo, String name, BirthDateShenClone birthday) {
    
    
        this.stuNo = stuNo;
        this.name = name;
        this.birthday = birthday;
    }
    @Override
    protected Object clone() throws CloneNotSupportedException{
    
    
        StudentShenClone stu =(StudentShenClone) super.clone();
        stu.birthday = (BirthDateShenClone)birthday.clone();
        return stu;
    }
}

CopyStudentShenClone.java

package c4.shenclone;

public class CopyStudentShenClone {
    
    
    public static void main(String[] args)throws CloneNotSupportedException {
    
    
        BirthDateShenClone birthday= new BirthDateShenClone(2000,1,1);
        StudentShenClone s1 = new StudentShenClone(202201,"张三", birthday);
        System.out.println(s1.getStuNo());
        System.out.println(s1.getName());
        System.out.println(s1.getBirthday());
        StudentShenClone s2 = (StudentShenClone)s1.clone();
        System.out.println(s1.getStuNo());
        System.out.println(s1.getName());
        System.out.println(s1.getBirthday());
        System.out.println("s2==s1:"+ (s2==s1));
        System.out.println("s2.birthday==s1.birthday:"+
                (s2.getBirthday()==s1.getBirthday()));
    }
}

insert image description here

Note that after the deep copy, the birthday of s1 and the birthday of s2 are no longer the same 同一.

The StudentShenClone of the two projects is actually the same, the difference is that the BirthDateShenClone rewrites the clone method;

The idea is:

既然引用类型不能实现深拷贝,那么我们将每个引用类型都拆分为基本类型,分别进行浅拷贝。

insert image description here

Object class (continued)—clone method—String class

The clone of the String type is quite special, so it is studied separately here;

String is not a basic data type, so what is the memory location of a String? There are two situations:

1. String direct assignment:

String s = "aa";   //String实例出来的对象是常量!

The reference of s is stored in the stack memory, and the "aa" pointed to by the reference is stored in the constant pool of the heap memory (first judge whether there is an "aa" in the constant pool, if it exists, point directly to it), no matter how many objects are created, they are all reference constants The string for the pool.
insert image description here

2. String object new creation

String s = new String("aa")

The reference of s exists in the stack memory, and the "aa" object pointed to by the reference exists in the heap memory (every new, a new "aa" object is created in the heap), and each variable will open up a new memory space to complete Stored regardless of whether the string is consistent or not.

insert image description here
Where is the particularity of String cloning? StringBufferand StringBuilderwhat?

Deep copy can be automatically implemented for basic data types . For reference types , it is a shallow copy.

Stringis a special case of a reference type. Because String is not allowed to be modified. So it is equivalent to a deep copy, which is safe. Since String is an immutable class, many modification operations in the String class are handled by copying new objects. So when we modify the value of the String property in the object before and after the clone, it actually points to a new memory space. Naturally, it has no effect on the source object before clone, similar to deep copy. Although it is a reference type, it does not affect our use of deep copy.
For StringBufferand StringBuilder, you need to actively clonerewrite. Otherwise it is a shallow copy.

What are the common ways to implement object cloning, and how to do it?
There are three commonly used methods.

  1. Through new a new object, assign value to realize deep cloning, which is cumbersome and error-prone.
  2. Implement Cloneablethe interface for the class to be cloned and rewrite the method Objectof the class , which can be divided into deep and shallow methods.clone
  3. Through Serializablethe interface and serialization and deserialization of objects to achieve real deep copy.

Object class (continued)—finalize() method

protected void finalize() throws Throwable 

Before the object is reclaimed by the garbage collector, the system automatically calls the finalize method of the object.
If the finalize method is to be overridden, it must be called at the end of the overridden method super.finalize().

Object class (continued)—getClass method

public final Class getClass() 

The final method returns a Class object, which is used to represent the class to which the object belongs.
Through the Class object, you can query various information of the Class object: such as its name, its base class, the name of the interface it implements, and so on.

void PrintClassName(Object obj) {
    
    
        System.out.println("The Object's class is " +
                       obj.getClass().getName());
}

Finalizers and Finalizers

终结类与终结方法
final修饰符修饰的类和方法
终结类不能被继承
终结方法不能被当前类的子类重写

终结类的特点

不能有派生类

终结类存在的理由

安全: 黑客用来搅乱系统的一个手法是建立一个类的派生类,然后用他们的类代替原来的类。
设计: 你认为你的类是最好的或从概念上你的类不应该有任何派生类。

终结方法的特点

不能被派生类覆盖。

终结方法存在的理由

  1. 对于一些比较重要且不希望子类进行更改的方法,可以声明为终结方法。可防止子类对父类关键方法的错误重写,增加了代码的安全性和正确性。
  2. 提高运行效率。当java运行环境(如java解释器)运行方法时,它将首先在当前类中查找该方法,接下来在其超类中查找,并一直沿类层次向上查找,直到找到该方法为止。

抽象类

抽象类
代表一个抽象概念的类
没有具体实例对象的类,不能使用new方法进行实例化
类前需加修饰符abstract
可包含常规类能够包含的任何东西,例如构造方法,非抽象方法
也可包含抽象方法,这种方法只有方法的声明,而没有方法的实现

抽象方法
声明的语法形式为

public abstract <returnType> <methodName>(...);

仅有方法头,而没有方法体和操作实现
具体实现由当前类的不同子类在它们各自的类声明中完成

抽象类可以包含抽象方法
只有抽象类才能具有抽象方法,即如果一个类中含有抽象方法,则必须将这个类声明为抽象类

抽象类的存在意义

  1. 基类定义为抽象类,如果不继承并实现其方法,不能创建实例对象,无法使用。
    Java里面不鼓励方法体的内容为空。
  2. 子类在继承父类时,要求子类必须重写父类中的抽象方法,起到一个提醒和约束的作用。

Example 1:
insert image description here
Example 2:
insert image description hereLoan is divided into many types, such as 租借(Lease), 抵押(Mortgage), 房屋贷款(HouseLoan), 汽车贷款(CarLoan)etc.
Declare Loan as an abstract class, and specify the behaviors that all subclass objects should have, such as 计算月还款值(calculateMonthlyPayment), 还款(makePayment), 取得客户信息(getClientInfo), where the first two are due to loan Different types of calculation methods are also different, and can be declared as abstract methods. All subclasses of Loan must rewrite these two abstract methods

public abstract class Loan {
    
     
        public abstract float calculateMonthlyPayment(); 
        public abstract void makePayment(float amount); 
        public Client getClientInfo() {
    
      } 
}

generic

Generics is a new feature of Java 5, which can make the Java language simpler and safer. Its essence is a parameterized type, that is, the type of data to be manipulated is specified as a parameter.

Generics can be used in the creation of classes, interfaces, and methods, which are called generic classes, generic methods, and generic interfaces. Generic
class: Add after the class name The <Type>
syntax is as follows:

[访问修饰符] class 类名称 <T1,T2,T3,....>

example:

public class Base <T>

use:

类名称 <T1,T2,T3,....> obj = new 类名称 <T1,T2,T3,....>( );

example:

Base<String> obj =new Base<String>();

Generic class example:

package chapter04.chapter04.generics;
class Base<T> {
    
    
    T m;
    Base(T t) {
    
    
        m = t;
    }
    public T getM(){
    
    
        return m;
    }
    public void print() {
    
    
        System.out.println("Base Type is: " +
                m.getClass().getName());
    }
}
public class GenericClass {
    
    
    public static void main(String[] args) {
    
    
        Base<String> base=new Base<String>("Type is String");
        System.out.println(base.getM());
        base.print();
        Base<Integer> base1=new Base<Integer>(111);
        System.out.println(base1.getM());
        base1.print();
    }
}

TThe specific type of the class is determined at the time of use here .
insert image description here
Generic methods
are mainly used for container classes. Any method in Java, including static (note that generic classes are not allowed to be used in a static environment) and non-static, can be defined with generics, and whether it is the same as the class it belongs to Generics don't matter.
definition

     [public] [static] <T> 返回值类型 方法名(T 参数列表)

Example:

package chapter04.chapter04.generics;

public class GenericMethod {
    
    
    public static <U> void print(U[] list) {
    
    
        System.out.println();
        for (int i = 0; i < list.length; i++) {
    
    
            System.out.print(" " + list[i]);
        }
    }
    public static void main(String[] args) {
    
    
        String a[]={
    
    "a","b","c","d","e"};
        Character b[]={
    
    '1','2','3','4','5'};
        Integer c[]={
    
    1,2,3,4,5};
        GenericMethod.print(a);
        GenericMethod.print(b);
        GenericMethod.print(c);
    }
}

insert image description here
The decision here Tis the type of variable used by the method

Generic meaning:

  1. 优点: Make the Java language easier and safer .
  2. In the absence of generics, the "arbitrary" of parameters is usually realized by reference to the type Object. The disadvantage of "arbitrary" is that mandatory type conversion must be done.

The programmer is required to know the type of the actual parameter in advance
. In the case of a mandatory type conversion error, the compiler may not prompt an error, and an exception will only occur at runtime, thus creating a security risk in the code.

  1. In the case of using generics, the compiler will check whether the type is safe, and all type conversions are automatic and implicit, which can improve code reuse.

Wildcard generics and restricted generics

Before Java 5, in order to make classes universal, attribute types, function parameters, and return types were often defined as Object classes.
Example:
insert image description here

Let's learn about wildcard generics and restricted generics

The following gives an error case that fails to compile:

package chapter04.chapter04.generics;
class GeneralType1 <Type> {
    
    
    Type object;
    public GeneralType1(Type object) {
    
    
        this.object = object;
    }
    public Type getObj() {
    
    
        return object;
    }
}
class ShowType {
    
    
    //public void showType(GeneralType1<Object> o) {
    
    
    public void showType(GeneralType1<Object> o) {
    
    
        System.out.println(o.getObj().getClass().getName());
    }
}
public class GenericTypeTester {
    
    
    public static void main(String args[]){
    
    
        ShowType st = new ShowType();
        GeneralType1 <Integer> i = new GeneralType1 <Integer> (2);
        st.showType(i); //这行语句是否合法?
    }
}

insert image description here
insert image description here

The above code does not compile, because you cannot pass General<Integer>a variable of type as a parameter toGeneral<Object>

In fact, the only type that can be passed here is General<Object>. Therefore, when using generics, you should pay attention to the difference from inheriting classes.
Using wildcard generics allows showTypethe function to behave as it should
?to represent any type, which is called a wildcard.
Corrected code:

package chapter04.chapter04.generics;
class GeneralType1 <Type> {
    
    
    Type object;
    public GeneralType1(Type object) {
    
    
        this.object = object;
    }
    public Type getObj() {
    
    
        return object;
    }
}
class ShowType {
    
    
    //public void showType(GeneralType1<Object> o) {
    
    
    public void showType(GeneralType1<?> o) {
    
    
        System.out.println(o.getObj().getClass().getName());
    }
}
public class GenericTypeTester {
    
    
    public static void main(String args[]){
    
    
        ShowType st = new ShowType();
        GeneralType1 <Integer> i = new GeneralType1 <Integer> (2);
        st.showType(i); //这行语句是否合法?
    }
}

insert image description here
Restricted generics
Sometimes it is necessary to restrict the types represented by the parameters in the generics. At this time, you can use the restricted generic
upper limit extends: the specified type or a subclass of this type.
Lower limit super: the specified type, or the parent class of this type, or the Object class.

Restricted generics refer to the use of the "extends" keyword and the class name or interface name after the parameter "Type", indicating that the type represented by the parameter must be a keyword of the class or implement the interface

注意,对于实现了某接口的有限制泛型,也是使用extends关键字,而不是implements关键字

insert image description hereinsert image description hereinsert image description here

Generics inheriting interfaces

interface MyInterface<T> {
    
    }

When implementing an interface, specify the generic type

class test1 implements MyInterface<String> {
    
    }

The implementation class also has generics

class test<T> implements MyInterface<T> {
    
    }

Composition of classes

Combination of classes
Java classes can have objects of other classes as members, which is the combination of classes

The syntax of composition is very simple, just put the objects of the existing class into the new class, you can
use has athe statement to describe this relationship

For example, considering that the Kitchen class provides functionality for cooking and refrigerating food, it is natural to say "my kitchen 'has a' cooker/refrigerator". So, simply put the objects myCooker and myRefrigerator in the class Kitchen. The format is as follows

class Cooker{
    
       // 类的语句  }
class Refrigerator{
    
       // 类的语句}
class Kitchen{
    
       
	   Cooker myCooker;
      Refrigerator myRefrigerator;
}

Portfolio project example:
insert image description here
The project structure is shown in the figure:
Point.java

package chapter04.chapter04.zuhe.line;

public class Point {
    
    
    private int x, y;
    public Point(int x, int y) {
    
     this.x = x; this.y = y;}
    public int GetX()  {
    
      return x; }
    public int GetY()  {
    
      return y; }
}

Line.java

package chapter04.chapter04.zuhe.line;

public class Line {
    
    
    private Point  p1,p2;     // 两端点
    Line(Point a, Point b) {
    
    
        p1 = new Point(a.GetX(),a.GetY());
        p2 = new Point(b.GetX(),b.GetY());
    }
    public double Length() {
    
    
        return Math.sqrt(Math.pow(p2.GetX()-p1.GetX(),2)
                + Math.pow(p2.GetY()-p1.GetY(),2));
    }
}

LineTester.java

package chapter04.chapter04.zuhe.line;
public class LineTester {
    
    
    public static void main(String args[]) {
    
    
        Point p1 = new Point(1,2);
        Point p2 = new Point(11,18);
        Line l1 = new Line(p1,p2);
        System.out.println(String.format("line's length :%.2f ",l1.Length()));
    }
}

insert image description here
Comparing Composition and Inheritance

  1. The "contains" relationship is expressed by combination.
    If you want to use the characteristics of an existing class inside the new class, but do not want to use its interface, you should usually choose combination. We need to embed the private object of the existing class in the new class. If you want the
    class When users directly access the components of the new class, they need to change the properties of the member objects to public
  2. The "belongs to" relationship is expressed using inheritance
    . Take an existing class and make a special version of it. Usually, this means that we are going to take a general-purpose class and customize it for specific needs

Combining Composition and Inheritance

Many times it is required to combine the two techniques of composition and inheritance to create a more complex class

The sequence of calling constructors for complex objects is:

  1. Call the base class constructor. This step will continue to be executed recursively, first constructing the root of the hierarchy, then the next layer of export classes, and so on, until the bottom export class;
    我--》父亲--》爷爷--》曾祖父--》高祖父--》太祖父
  2. Invoke the constructors of members (other class instance objects) in the order of declaration;
  3. Call the constructor of its own class.

Example:

package chapter04.chapter04.zuhe.jicheng;
class Meal{
    
    
    Meal() {
    
    
        System.out.println("Meal Constructor");
    }
}
class Bread{
    
    
    Bread(){
    
    
        System.out.println("Bread Constructor");
    }
}
class  Cheese{
    
    
    Cheese(){
    
    
        System.out.println("Cheese Constructor");
    }
}
class Lettuce{
    
    
    Lettuce(){
    
    
        System.out.println("Lettuce Constructor");
    }
}
class Lunch extends Meal{
    
    
    Lunch(){
    
    
        System.out.println("Lunch Constructor");
    }
}
class PortableLunch extends Lunch{
    
    
    PortableLunch(){
    
    
        System.out.println("PortableLunch Constructor");
    }
}
public class ZuHeJiChengOrder extends PortableLunch {
    
    
    private Bread b=new Bread();
    private Cheese c=new Cheese();
    private Lettuce l=new Lettuce();
    public ZuHeJiChengOrder(){
    
    
        System.out.println("ZuheJichengOrder Constructor");
    }
    public static void main(String[] args){
    
    
        new ZuHeJiChengOrder();
    }
}

insert image description here

JAVA basic library

Java Basic Class Library
Java provides a class library for language development, called Java Basic Class Library ( JFCJava Foundational Class), also known as Application Programming Interface ( APIApplication Programming Interface), which are placed in different packages.
Java provides The packages mainly include

java.lang,java.io,java.math,java.util
java.applet,java.awt,java.awt.datatransfer
java.awt.event,java.awt.image,java.beans
java.net,java.rmi,java.security,java.sql等

java语言包 java.lang

语言包(java.lang)
语言包java.lang提供了Java语言最基础的类,包括

Object类
数据类型包裹类(the Data Type Wrapper)
字符串类(String、StringBuffer)
数学类(Math)
系统和运行时类(System、Runtime)
类操作类(Class,ClassLoader)

数据包裹类
对应Java的每一个基本数据类型(primitive data type)都有一个数据包裹类

数据包裹类的意义:

将一个基本数据类型的数据转换成对象的形式,使它们可以像对象一样参与运算和传递。

每个包裹类都只有一个类型为对应的基本数据类型的属性域

insert image description here
生成数据类型包裹类对象的方法
从基本数据类型的变量或常量生成包裹类对象

double x = 1.2;
Double a = new Double(x);
Double b = new Double(-5.25); 

从字符串生成包裹类对象

Double c = new Double("-2.34");
Integer i = new Integer("1234"); 

已知字符串,可使用valueOf方法将其转换成包裹类对象:

Integer.valueOf("125");
Double.valueOf("5.15");

自动装箱

Integer i =3; Double d = -5.25

得到基本数据类型数据的方法
每一个包裹类都提供相应的方法将包裹类对象转换回基本数据类型的数据

anIntegerObject.intValue()   // 返回 int类
aCharacterObject.charValue() // 返回 char类型的数据

Integer, Float, Double, Long, Byte, and Short classes provide special methods that can directly convert objects of type string to corresponding data of type int, float, double, long, byte, or short

Integer.parseInt(234)        // 返回int类型的数据
Float.parseFloat(234.78)     // 返回float类型的数据

Automatic unboxing

Integer a = new Integer(3); int i = a;

Boxing and unboxing

Boxing: wrap basic type data into objects, such as:

Integer obj = new Integer(8);

Unboxing: Extract the basic data inside the object.
It must be assembled first and then disassembled, such as:

Boolean objb = new Boolean(false);      //装箱
boolean b = objb.booleanValue();          //拆箱

Two methods of packing:

(1)调用数据封装类构造方法,如:
   Integer obj = new Integer(i),设int i = 8。
(2)(应优先采用)调用封装类数据转对象的静态方法,如:
    Integer obj = Integer.valueOf(i)。

The data encapsulation class also provides some static constant fields, such as:

Integer.MAX_VALUE:int型最大值2147483647Integer.MIN_VALUE:int型最小值-2147483648

The data encapsulation class also provides methods for converting to and from the String type. Such as Integer class method:

toString(int i)parseInt(String s)

Autoboxing and autounboxing
Automatic conversion between primitive data and objects of corresponding encapsulation classes. like:

       Integer obj = 8;     //自动装箱,

Equivalent to Integer obj = new Integer(8);
automatic unboxing example:

int i = obj;                             //自动拆箱,拆箱后再赋值
int sum = obj + obj;             //自动拆箱,拆箱后再进行加法运算 
Integer obj2 = obj + obj;    //自动拆箱后相加,再自动装箱为对象

Equivalent to the following unboxing and boxing statements:

int i = obj.intValue();
int sum = obj.intValue() + obj.intValue();
Integer obj2 = Integer.valueOf(obj.intValue() + obj.intValue());

It is because of the automatic boxing operation that the ArrayList set whose default element type is Object can directly add basic types of data such as char, int and double.

Note: Automatic boxing and unboxing will reduce the efficiency of the program, so use it with caution.

String class

String类
The value and length of this type of string object do not change,
which is called a constant string.
The method of generating a String class object
can generate a constant string like this

String aString;
aString =This is a string” 

Call the constructor to generate a string object

new String();           
new String(String value); 
new String(char[] value); 
new String(char[] value, int offset, int count); 
new String(StringBuffer buffer);

Common methods of the String class
insert image description here
insert image description here

variable string class StringBuffer

StringBufferClass
whose object is a string that can be modified.
The number of characters is called the length of the object ( length)
The storage space allocated is called the capacity of the object ( capacity) Compared
with Stringthe object of the class, the execution efficiency is lower. The
method of this class cannot be used Objects of the String class

Generate an object of the StringBuffer class

new StringBuffer(); 
//生成容量为16的空字符串对象
new StringBuffer(int size); 
//生成容量为size的空字符串对象
new StringBuffer(String aString); 
//生成aString的一个备份,容量为其长度 +16

Mathematics (Math)

Mathematics class
Provides a set of constants and mathematical functions, such as methods for calculating
E和PI常数
absolute values , sin and cos methods for calculating trigonometric functions, min and max methods for finding minimum and maximum values, random methods for finding random numbers, and all other variables and methods All static (static) is a final class (final), and other new classes cannot be derived from itabs




Calculate random numbers
java.lang.Math.random();
java.util.Random class
Get system time System.currentTimeMillis()

java.lang.Math.random();
Calling this Math.random() function can return a double value with a positive sign, which is greater than or equal to 0.0 and less than 1.0, that is, the value range is [0.0,1.0) in the left-closed right-open interval, and the return value is a pseudo-random selection The number of is (approximately) uniformly distributed in this range.

java.util.Random
Two construction methods of the Random class: :
Random()Create a new random number generator.
Random(long seed): Creates a new random number generator with a single long seed.
You can specify the seed when constructing the Random object, such as:
Random r1 = new Random(20);
or default the number of milliseconds of the current system time as the seed number:
Random r1 = new Random();
It should be noted that any legal seed number can be given when creating a Random object, and the seed number is just random The origin number of the algorithm has nothing to do with the interval of the generated random number.

java.util.RandomThe class method
insert image description heregenerates a decimal in the [0,1.0) interval: double d1 = r.nextDouble();
generates a decimal in the [0,5.0) interval: double d2 = r.nextDouble() * 5;
generates a decimal in the [1,2.5) interval: double d3 = r.nextDouble() * 1.5 + 1;
generates a random integer: int n = r.nextInt();
generates an integer in the [0,10) interval:

int n2 = r.nextInt(10);//方法一
n2 = Math.abs(r.nextInt() % 10);//方法二

JAVA utility package (java.util)

Utilities package (java.util) - implement various utility functions
Date class: describe date and time

Date
Calendar
GregorianCalendar

collection class

Collection (unordered collection), Set (non-repeated collection)
List (ordered non-repeated collection), Enumeration (enumeration),
LinkedList (linked list), Vector (vector)
Stack (stack), Hashtable (hash table), TreeSet (tree )

StringTokenizer class

Allows a string to be separated into individual substrings by some separation criterion

Date class

Constructor
Date()Gets the system's current date and time value.
Date(long date) Create a date object with date, which represents the number of milliseconds from 1970-1-1 00:00:00 GMT (Greenwich Mean) time to a certain moment.
Common methods
getTime()
Return a long integer to represent the time, and the unit is millisecond (millisecond)
after(Date d)
return Whether the date indicated by the receiver is after the given date
before(Date d)
Returns whether the date indicated by the receiver is before the given date

JAVA text package (java.text)

Various text or date formats are available, including

Format类(抽象类)
DateFormat类(抽象类)
DateFormat df = DateFormat.getDatelnstance();
      //得到SimpleDateFormat对象
SimpleDateFormat类(是DateFormat的子类)

Formats a date object using a defined format.
The constructor takes a string specifying the format as a parameter

new java.text.SimpleDateFormat(formatString);
format(Date d)  将此种格式应用于给定的日期
aSimpleDateFormat.format(aDate);

custom package

Custom package
A package is a collection of classes. Using packages to manage classes can realize class sharing and reuse.
Classes in the same package can access each other by default. Usually, classes that need to work together are placed in a package. In
actual use, users can organize their own classes into package declarations.
Package
names are usually all in lowercase letters
and each package name must be "unique". To avoid package name conflicts, the organization's Internet The reverse order of the domain name, as the prefix of the package name
For example:

cn.edu.tsinghua.computer.class0301

declaration statement

package mypackage;

Indicates that all classes declared in the current file belong to the package mypackage.
Each class name in this file has a prefix mypackage, that is, the actual class name should be mypackage.ClassName, so the same class name in different packages will not conflict
insert image description here

Guess you like

Origin blog.csdn.net/qq_51594676/article/details/124853060