A, polymorphism

1. Polymorphism is aimed atobjectIs not a class

2. Format:Object name = new Subclass name ()

Or interface name Object name = new Implementation name ()

3. In case of citation

Call a member variable directly, first look for the parent class, if there is no up to call a member method directly, first look for a child class, if there is no up to call a member variable indirectly, who belongs to the method, then call whose member variable

4. Contrast

Member variables: Compile to the left (parent), run to the left (parent) Member methods: Compile to the left (parent), run to the right (child)

5. Polymorphic benefits

Polymorphism is a better abstraction

Employee  teacher = new Teacher();
teacher.work();/ / to teach
Employee assistant = new Assistant();
assistant.work();// Correct the homework
Copy the code

6. Security

  1. Upcasting must be safe, but subclass-specific methods cannot be called

Animal animal = new Cat();

  1. Downward transformation is on the basis of upward transformation, in essence is a reduction action
Animal animal = new Cat();
Cat cat = (Cat)animal;
Copy the code

7. Polymorphic judgment problem

1. How can I determine a reference object of a superclass type, the original subclass type

/* Determine if the parent class referring to animal is of Dog type */
if(animal instanceof Dog){
    Dog dog = (Dog)animal;
    dog.watchHouse();
}
Copy the code

8. The benefits of polymorphism


/* If the parent class is used as a method parameter, you can pass in a subclass */
public static void main(String[] args){
    giveMeAPet(new Dog());
    giveMeAPet(new Cat());
}

public static void giveMeAPet(Animal animal){
    if(animal instanceof Dog){
        Dog dog = (Dog)animal;
        dog.watchHouse();
    }
    if(animal instanceofCat){ Cat cat = (Cat)animal; cat.catchMouse(); }}Copy the code

Inner class

Classification of 1.

A. Member inner class B. Local inner class (including anonymous inner class)

2. Member inner classes

public class Body {
    public class Heart{... }}Copy the code

The output format of the compiled file is

Body.class Body$Heart.class

1). Variable name problem

public class Outer{
    int num =10;
    public class Inner{
        int num =20;
        public void MethodInner(a){
            int num =30;
            System.out.println(num);/ / 30
            System.out.println(this.num);/ / 20
            System.out.println(Outer.this.num);/ / 10}}}Copy the code

3. Local inner classes

Defined in the body of a method and cannot be modified with a modifier

1). Final problems with local inner classes

/* Local inner class. If you want to access a local variable of the method, the local variable must be final (either with the final keyword, or assigned only once). 1. New object in heap memory 2. When a local variable follows a method, it is in the stack memory. 3. After the method is run, it is immediately out of the stack, and the local variable will disappear immediately. If methodOuter() runs out of stack memory and disappears, and the new Inner object still needs to call a local variable in methodOuter(), define the local constant as final. Inner objects make a copy of local variables for their own use, preventing local variables from disappearing off the stack with the method */
public class MyOuter{
    public void methodOuter(a){
        int num =10;
        class Inner(a){
            public void methodInner(a){ System.out.println(num); }}}}Copy the code

4. Anonymous inner classes

Key mastery will serve as the basis for lambda expressions

1). Usage

If the implementation class of the interface (or a subclass of its parent class) needs to be used only once, the class definition can be omitted in favor of an anonymous inner class


/* If the implementation class of the interface (or a subclass of its parent class) needs to be used only once, then the class definition can be omitted and the anonymous inner class format can be used instead: interface name/superclass name Object name = new interface name/superclass name (){// Override all abstract methods}; * /
public static void main(String() args){
    //myInterface oby = new MyInterfaceImpl();
    //obj.method();
    
    // Use anonymous inner classes
    MyInterface obj = new MyInterface(){
        @Override
        public void method(a){
            System.out.println("Anonymous inner classes implement methods"); }}; obj.method(); }Copy the code

2). Precautions

A. An anonymous inner class can only be used once when creating an object

B. Anonymous objects can only be used once when [method is called]

C. Anonymous inner classes omit the implementation class/subclass name, but anonymous objects omit the object name, which is not the same thing

D. Anonymous inner classes cannot have static content. Anonymous inner classes are later than class loading, and static content follows class loading.

Some methods in the Object class

1. toString()

To print an Object directly is to call the Object’s toString() method, or, if the Object’s class has not overridden the method, toString(), which in the case of Object, prints the address value

Both the popular Scanner and ArrayList classes override the toString() method

2. The equals () method

String s1 = null;
String s2 = "abc";

boolean b = s1.equals(s2);// error null pointer exception

boolean B = Objects.equals(s1,s2); // Tolerate null pointer exception errors
Copy the code

Variable parameters

1. Precautions

  1. The argument list of a method can have only one variable argument
  2. If a method has more than one parameter, the variable parameter must be written at the end of the parameter list

2. Code examples

public static int add(int. arr){
    int sum =0;
    for(int a:arr){
        sum += a;
    }
    return sum;
}
Copy the code

3. Special writing of variable parameters

public static void method(Object ... obj){ ... }

Five, abnormal

1. Treatment mechanism diagram

2. Common keywords used to handle exceptions

1). Throw an exception

A. how it works:

You can use the throw keyword to throw a specified exception in a specified method

B. Use format:

Throw new xxxException(" exception cause ");

C. Precautions

A).throw must be written inside a method b).throw must be an Exception or a subclass of Exception c).throw must throw the specified Exception object, and we must handle: The throw keyword is followed by a RuntimeException or a subclass of RuntimeException, which we do not need to handle. By default, we hand it to the JVM (print exception objects, interrupt programs). Throw (throw) throws throw (throw){throw (throw){throw (throw){throw (throw){throw (throw);

/* The argument passed by the method must be validated first. If the argument is not valid, the method caller must throw an exception to inform the method caller that the argument passed is not valid */
public static int getElement(int[] arr,int index){
    If the array arr is null, throw a null pointer exception and tell the method caller "the array passed is null" */
    
    if(arr == null) {NullPointerException is a RuntimeException
        throw new NullPointerException("The value of the array passed is null");
    }
    int ele = arr[index];
    return ele;
    
}
Copy the code

Note: static methods in the Objects class

Public static

T requireNonNull(T obj): Checks that the specified reference object is not null

Source:

public static <T> T requireNonNull(T obj){
    if(obj == null) {throw new NullPointerException();
    }
    return obj;
}

Copy the code

The above code can be optimized as

public static void method(Object obj){
    Objects.requireNonNull(obj);
    / / overloaded
    Objects.requireNonNull(obj,"The value of the array passed is null");
}
Copy the code

Throws exception throws

A. role

When an exception object is thrown inside a method, we must process it. We can use the throws keyword to process the exception object. The exception object declaration is thrown to the method caller for processing (not himself, but for other processing), and finally to the JVM for processing (interrupt processing)

B. format

After the method name

public void method(a) throws xxxException,yyyException{
    throw new xxxException("Cause of occurrence");
    throw new yyyException("Cause of occurrence");
}
Copy the code

C. Precautions

  1. throwsThe keyword must be written in the method declaration
  2. throwsThe exception declared after the keyword must beExceptionOr subclasses thereof
  3. Method if declared insideMultiple exception objects, thenthrowsThis must also be stated laterMultiple abnormalIf thethrowThe exception object ofInheritance relationships, direct declarationThe parent classThe exceptions
  4. If you call a method that claims to throw an exception, you must either handle the declared exception or continue using itthrowsDeclare the throw, hand it over to the method caller, and finally hand it overJVM, ortry{}catch(){}Handle exceptions yourself
  5. If the methodthrowIs the exception object ofCompile the abnormal, the method name requiresthrowsCompile the abnormal

3). Catch an exception try catch

[A]. The meaning of existence

When you want to execute the subsequent code of the exception (throws requests the JVM interrupt program), you catch the exception yourself, execute catch(){}, and continue the subsequent code execution

B. format

try{code that may generate an exception}catchDefine an exception variable to receivetryException handling logic, generally recorded in a logreturn;// Can end the program}...catch() {/ / catch there can be multiple, but the exception object if there is a hierarchy, the subclass exception variable must be written in the book of the above, otherwise an error, because the polymorphism, the JVM find abnormal object types in the catch order, if the parent class before, and can point to the parent class subclass references (although subclasses variable definition, but not used), but not detailed, so you need to report errors
}
Copy the code

C. Common methods of exception objects

  1. getMessage()Print a short description
  2. toString()Print details
  3. printStackTrace()The JVM prints the most comprehensive method that the exception object calls by default

4).finally code block

A. role

Some code needs to be executed whether or not an exception occurs. Finally can be used to declare that any code in the finally block must be executed. In the case of a try catch, the statement after the catch can be executed, but not the statement after the try

B. format

/* 1. It must be used with a try. 2. It is usually used for resource release (resource recovery)
public static void main(String[] args){
    try{
        readFile("test.txt");
    }catch(IOException e){
       e.printStackTrace(); 
    }finally{
        // Execute regardless of whether an exception occurs, so it is best not to write return here
        System.out.println("Resource Release"); }}Copy the code

5.)

Compile-time exceptions must be handled at the code level. Throw or try catch run-time exceptions may not be handled at the code level and the JVM will interrupt processing

3. Customize exception classes

1.) format

public class xxxException extends Exception | RuntimeException{Add a null parameter constructor Add a constructor with exception information}Copy the code

2). Pay attention to

  1. Custom Exception classes generally end with Exception
  2. Custom exception classes must be inheritedExceptionorRuntimeException

    Among themExceptionRepresents a compile-time exception. If a compile-time exception is thrown inside a method, it must be handled, either with throws or a try catch

    RuntimeExceptionIndicates a runtime exception, and no action is required

3). The code

/* Use the parent method */
public RegisterException extends Exception{
    public RegisterException{
        super(a); }public RegisterException(String message){
        super(message); }}Copy the code

Concurrency and parallelism

Concurrency: alternate execution

Parallel: simultaneous execution

Lambda expressions

JDK1.8 new features

0. Prerequisites

  • To use lambda expressions, an interface must have one and only one abstract method in the interface, and an interface with one and only one abstract method is called a functional interface
  • The use of lambda expressions requires contextual inference, that is, the type of the argument or local variable of a method must be the type of the interface to which lambda corresponds before lambda can be used as an instance of that interface

1. Object-oriented thinking

Do something, find an object that solves it, call its methods, and do it

2. Functional programming idea

It doesn’t matter who does it, how you do it, as long as you get the results, just the results, not the process, right

3. Code

public static void main(String[] args){
    // Implement multithreading with anonymous inner classes
    new Thread(new Runnable(){
        @Override
        public void run(a){     System.out.println(Thread.currentThread().getName()+"New thread created");
        }
    }).start;
    
    
    // Multithreading with lambda expressions
    new Thread(()->{
        System.out.println(Thread.currentThread().getName()+"New thread created");
    }).start;
}
Copy the code

4. Standard format

A lambda expression consists of three parts:

(Parameter list) -> {some code to override methods}

  • Some of the parameters

Omitted if the parameter data type is derived from context if there is only one parameter in parentheses, both the data type and () can be omitted

  • An arrow

Pass the parameters to the method body

  • A piece of code

If there is only one line of code, the return {}; Both may be omitted, but both must be omitted

Eight, the File

  1. On Windows, the pathSeparator is; Separator is \

  2. The file separator in Linux is: The file name separator is /

  3. Separator is a File name separator that can be used to obtain the system string type

  4. Print a file object that overrides the toString() method, getPath(). In fact, it prints its path

    public String toString(a){
        return getPath();
    }
    Copy the code
  5. Commonly used method

  • To obtain

public String getAbsolutePath()

public String getPath()

Public String getName() // Returns the file or directory name

Public long length() // in bytes

  • judge

public boolean exists()

public boolean isDirectory()

public boolean isFile()

  • Create a delete

Public Boolean createNewFile() // The path to create the file must exist. Otherwise, IOException is thrown

Public Boolean delete() // Delete files or folders from the hard disk without going to the recycle bin. Exercise caution when deleting files or folders

public boolean mkdir()

Public Boolean mkdirs() // Create the directory represented by this File, including any required but non-existent parent directories, i.e., multi-level folders

  • Directory traversal

Public String[] list() // Returns an array of files representing all subfiles or directories in the File directory. Hidden files can also be retrieved

Public File[] listFiles() // Returns a File array representing all subfiles or directories in the File directory. Hidden files can also be retrieved

  • File filter

listFiles(FileFilter filter)

    File[] files = dir.listFiles(new FileFilter(){
        @Override
        public boolean accept(File pathName){
            // Return true to return the original File path to the method caller listFiles(FileFilter filter) method, stored in the File[] array
            return pathName.getName().endsWith(".java"); }});/ / lambda expressions
    File[] files = dir.listFiles(pathName -> pathName.getName).endsWith(".java"));
    
Copy the code

listFiles(FilenameFilter filter)

    / / lambda expressions
    File[] files = dir.listFiles((dir, name)->name.getName().endsWith(".java"));
Copy the code

Nine, IO

1. The output stream

1). The illustration

Input and output data is read from disks, and output data is written to disks

2). Storage principle and opening principle

Java program –> JVM –> OS –> system local file writing method –> write files to hard disk

3). Common methods

FileOutputStream extends OutputStream
/ / written

FileOutputStream(String name,boolean append) // Create an output stream that writes data to a file with the specified name. Append is the continuation switch, true to continue, false to overwrite the file

FileOutputStream(File file,booleanAppend) ditto/ / a newline

/* Windows: \r\n Linux: /n MAC: /r */

FileOutputStream fos = new FileOutputStream("\\c.txt");
fos.write("\r\n".getBytes());

fos.close();
Copy the code

2. The output stream

1). The illustration

The read() method moves back one bit after reading

Both the third and fourth reads result in ED

2). Reading principle

Java program –> JVM –> OS –> system native method of reading files –> read files from the hard disk

3). Common methods

Int read(byte[] b) reads a certain number of bytes from the input stream and stores them in the buffer array B to make two things clear: 1. Method argument byte[]? Buffers multiple bytes that are read at a time, typically defined as 1024(1kB) or multiple of 1024. What is the return value int of the method? Number of valid bytes read each time */

FileInputStream fis = new FileInputStream("\\b.txt");

byte[] bytes = new byte[1024];
int len =0; 
while((len = fis.read(bytes)) ! = -1){
    System.out.println(new String(bytes,0,len));//ABCDE
}

fis.close();
Copy the code

3. Copy files

FileOutputStream fos = new FileOutputStream("\\des.jpg");
FileInputStream fis = new FileInputStream("\\src.jpg");

byte[] bytes = new byte[1024];
int len =0;
while((len = fis.read(bytes)) ! = -1){
    fos.write(bytes);
}

// Close the output stream first (write)
// Close the input stream (read)

fos.close();
fis.close();
Copy the code

4. Character input and output streams

1). Problems in byte stream reading Chinese

In Windows, a Chinese character is two bytes

A Chinese character is three bytes in Linux

2.)

The byte stream subclass ends with the abstract class InputStream /outputstream

The character stream subclass ends with the abstract reader/ Writer class

The byte stream is in bytes and the character stream is in characters. The operation of reading and writing is similar

3). Commonly used class

Java.io.FileReader extends InputStreamReader extends Reader // file character input stream

5. Other methods

  • flush():

Flush the buffer to the file and the stream object can continue to be used

  • close():

Flush buffer to file, stream object closed, no longer usable

6. Exception handling

/* JDK1.7 automatically releases a try after it is used (create stream object; Create a stream object... Catch (exception object){exception logic handling} */

/ * JDK1.9 A, A. B b; Try (a,b){catch(exception object){exception logic handling} */
Copy the code

7. The buffer flow

1). The illustration

2). Commonly used class

BufferedOutputStream

BufferedInputStream

BufferedWriter

BufferedReader

3). Construction method

  1. BufferedOutputStream(OutputStream out)// creates a new BufferedOutputStream to write data to the specified underlying OutputStream

  2. BufferedOutputStream(OutputStream out,int size)// creates a new BufferedOutputStream to write data with the specified buffer size to the specified underlying OutputStream

    Params: OutputStream out: byte output streams can pass FileOutputStream. Buffers add a buffer to FileOutputStream, improving FileOutputStream writing efficiency

1. Create a byte output stream object
FileOutputStream fos = new FileOutputStram("\\des.txt");

//2. Create a byte output buffer stream object
BufferedOutputStream bos = new BufferedOutputStram(fos);

//3. Call the write() method of the byte output buffer stream object to write data to the memory, while the data does not enter the disk file
bos.write("Write data to an internal buffer".getBytes());

//4. Call the byte output buffer stream object's flush() method to flush the data in memory to the disk file
bos.flush();

//5. Close the byte output buffer stream object to release resources. The close() method calls flush() first, so step 4 can be omitted
bos.close();



Copy the code

8. Transformation flows

1.) encoding

Structure of a.

B. Utf-8 encoding table

[C]. Common problems

FileReader can read files in the IDE default encoding format (UTF-8)

FileReader Reading the default system encoding (GBK) generates garbled characters

D. Solutions

Transformation flows

2). Change the flow of solutions

A. the illustration

B. code


/* OutputStreamWriter extends FileWriter because FileWriter cannot specify an encoding for writing to a file
public void write_utf_8(a) throws IOException{
    //1. Create an OutputStreamWriter object with the constructor passing the byte output stream and specifying the encoding table name
    OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream("utf-8test.txt"),"utf-8");
    
    //2. Use the OutputStreamWriter method write to convert characters to byte storage buffers
    osw.write("Hello");
    
    //3. Run Flush to flush the data in the buffer to the disk file
    osw.flush();
    
    //4. Release resources
    osw.close();
}

Copy the code

9. Serialized and unserialized streams

1.)

The input and output of byte or character files have corresponding byte streams FileInputStream,… Or character stream, FileReader,…

If you need to save an object to a file, you need streams to write and read the object

ObjectOutputStream serializes an object stream. This process is called object serialization. WriteObject (Obj Object)

ObjectInputStream object deserialization stream. This process is called object deserialization. The function called readObject(Obj Object)

2). The illustration

3.) the point

  • forSerialization, deserializationObject, whose classes must beimplements Serializable
  • SerializableforLabeled interface(There is no code in its interface)
  • When deserializing,ObjectInputStreamthereadObject()There are alsoClassNotFoundException
  • Deserialized objects must exist in a class file of their class
  • When deserializing, the class file is found, but is thrown if the class file changes after serializationInvalidClassException
  • serialVersionUID

  • staticThe decorated member variable cannot be performedserializationBecause itsGeneral takes precedence over objectLoad, can achieve serialization isobject
  • transient(transient) modified member variables also cannot be serialized, soMember variables that do not require serialization(or to save space, or can be derived), can be usedtransientModification (staticRetouching is inconvenient)

4.)

A. the serialization

public class Person implements Serializable{... }Copy the code


public static void main(String[] args) throws IOException{
    //1
    ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("\\person.txt"));
    
    //2. Write the object as follows
    oos.writeObject(new Person("Guo jing".20));
    
    //3. Release resources
    oos.close();
}
Copy the code

B. Deserialize

public static void main(String[] args) throws IOException, ClassNotFoundException{
    //1
    ObjectInputStream ois = new ObjectInputStream(new FileInputStream("person.txt"));
    
    //2. Read the object function as follows
    Object obj = ois.readObject();
    
    //3. Release resources
    ois.close();
    
    //4. Print the read object
    System.out.println(obj);
}
Copy the code

10. Printing flow

public static void main(String[] args) throws FileNotFoundException{
    System.out.println("Output on console");
    
    // Create a print stream
    PrintStream ps = new PrintStream("destinationIsChanged.txt");
    
    // Change the purpose of the output statement
    System.setOut(ps);
    
    / / test
    System.out.println("Output at destinationischanged.txt");
    
    // Release resources
    ps.close();
    
}
Copy the code

Properties collection

java.util.Properties extends HashTable<k,v> implements Map<k,v>

Characteristics of 1.

  1. Represents a persistent set of properties that can be saved in or loaded from a stream
  2. The Properties collection is the only collection associated with streams
  3. Key and value are strings by default

2. Common methods

  1. Object setProperty(String Key,String Value) // Call the put() method in Hashtable

  2. String getProperty(String key)// Get value by key

  3. Set<String> stringPropertyNames() // returns the keySet of this property list, equivalent to the keySet() method in the Map collection

  4. Void store(OutputStream out,String Comments) // Write temporary data to disk persistently

  5. void store(Writer writer,String comments)

    params:

    OutputStream out: byte OutputStream, cannot write Chinese

    Writer Writer: character output stream that can be written in Chinese

    String comments: comments to explain the purpose of the saved file. Generally, “” is used. Chinese cannot be used, garbled characters will be used, and Unicode is used by default

// Default key values are String
Properties prop = new Properties();
prop.setProperty("machieal"."11");

FileWriter fw = new FileWriter("\\test.txt");

prop.store(fw,"save data");

fw.close();
Copy the code
  1. Void load(InputStream in) // Load files (key-value pairs) stored in the hard disk into the collection

  2. void load(Reader reader) params:

    InputStream in: byte InputStream that cannot read key/value pairs containing Chinese characters

    Writer Writer: a character input stream that can read key/value pairs containing Chinese characters

    Notices

    A. In files storing key-value pairs, the default concatenation for key-value pairs can use =, space (or other symbols)

    B. In files that store key-value pairs, you can comment them with #. The annotated key-value pairs will not be read again

    C. In files that store key-value pairs, the key-value pairs are strings by default without quotation marks

1. Create a collection object
Properties prop = new Properties();

//2. Load () in the Properties collection object is used to read files
prop.load(new FileReader("\\prop.txt"));

//3. Iterate through the Properties collection
Set<String> set = prop.stringPropertyNames();

for(String key : set){
    String value = prop.getProperty(key);
    System.out.println(key + "=" + value);
}


Copy the code