This Java interview basics notes read, stable!

Wechat search “village yuyao”, pay attention to me, grow up together!

Personal blog: Village Rain Remote grocery store

0. Getting started

Java 0.1 features

  1. Easy to learn
  2. Object oriented (encapsulation, inheritance, polymorphism)
  3. Platform independent
  4. Safe and reliable
  5. Multithreading support
  6. Interpretation and compilation coexist
  7. security
  8. Robustness (Java language’s strong typing mechanism, exception handling, automatic garbage collection, etc.)

Java and c + + 0.2

  • Similarities: Both OOP languages support three OOP features (encapsulation, inheritance, polymorphism);
  • The difference between:
    • Java doesn’t have Pointers, so memory is safer;
    • Java classes are single-inherited (but interfaces can be multi-inherited), C++ classes are multi-inherited;
    • Java has automatic memory management, but C++ requires developers to manually free memory.
    • In C/C++, both strings and character arrays end with an extra\ 0Flag to indicate closure, but this concept does not exist in Java;

0.3 the JRE and JDK

  • The Java Runtime Environment (JRE) is a collection of contents (such as the JVM, Java class libraries, and Java commands) required by compiled Java programs. It cannot be used to develop new programs.
  • The JDK (Java Development Kit), or Java Development Kit, is a full-featured Java SDK that contains everything the JRE has, as well as a compiler and other tools that we must use if we want to create and compile new programs;

0.4 Java program compilation process

The source code we compiled (xxx.java) is compiled by the JAVac command in the JDK into Java bytecode (xxx.class) that the JVM can understand, then loaded by the JVM and interpreted line by line by the interpreter. This is why it is often said that Java is a language where compilation and interpretation coexist.

The JVM is a virtual machine that interprets Java bytecode (XXx. class). It has specific implementation for different systems, which is convenient for one compilation and many runs, that is, the platform independence of Java language.

1. Data types

1.1 Basic data types

The data type bit byte Wrapper class Data range The default value
byte 8 1 Byte
2 7 – 2 ^ 7
~
2 7 1 2 ^ 7-1
0
short 16 2 Short
2 15 – 2 ^ {15}
~
2 15 1 2 ^ {15} – 1
0
char 16 2 Character \u0000 ~ \uffff(
0 0
~
65535 65535
)
u0000
int 32 4 Integer
2 31 – 2 ^ {31}
~
2 31 1 2 ^ {31} – 1
0
long 64 8 Long
2 63 – 2 ^ {63}
~
2 63 1 2 ^ {63} – 1
0L
float 32 4 Float
3.4 e 45 3.4 e ^ 45} {-
~
1.4 e 38 1.4 e ^ {38}
0.0 f
double 64 8 Double
4.9 e 324 4.9 e ^ {324}
~
1.8 e 308 1.8 e ^ {308}
0.0 D
boolean Not sure Not sure Boolean truefalse false

Note:

  1. booleanGenerally in 1bitTo store, but the size is not specified, the JVM will at compile timebooleanType conversion toint, where 1 representstrue.0On behalf offalse. In addition, the JVM points out thatbooleanArray, but the underlying is throughbyteArray to implement;
  2. uselongType, need to be appendedLOtherwise, parsing it as an integer may result in transgression;
  3. Floating point number if not explicitly specifiedfloatordouble, according to thedoubleProcessing;
  4. charIs to useSingle quotes' 'Enclose the contents, equivalent to an integer value (ASCII value), can participate in expression operations; whileStringIs to useDouble quotation marks""Enclosed contents represent an address value;

1.2 Reference Types

The data type The default value
An array of null
class null
interface null

1.3 wrapper class

Each basic data type has its corresponding encapsulation class, and the assignment between them is completed by automatic boxing and automatic unboxing.

  • Automatic boxing: Boxing basic data types into encapsulated classes;
// Actually call integer.valueof (12)
Integer x = 12;
Copy the code
  • Automatic unpacking: unpacking the packaging class as the basic data type;
Integer x = 12;
// Actually call x.intValue()
int y = x;
Copy the code
  • The difference between the base type and the corresponding wrapper class
    1. Primitive types can only be passed by value, and encapsulated classes by reference.
    2. Basic types are created on the stack, which is efficient, but can have memory leaks. Encapsulating class objects are created in the heap and their references are created in the stack;

1.4 buffer pool

For example, new Integer(123) and integer.valueof (123) :

  • throughnewCreates a new object each time;
  • throughvalueOf()If the value is in the cache pool, it directly returns the contents of the cache pool, and calls the reference to the same object multiple times.
Integer x = new Integer(123);
Integer y = new Integer(123);
// false, with the new method, a new object is created each time, pointing to a different object
System.out.println(x == y);    
Integer m = Integer.valueOf(123);
Integer n = Integer.valueOf(123);
ValueOf (); // true, the cache pool is searched by valueOf ()
System.out.println(m == n);   
Copy the code
The data type Default cache pool
Byte
2 7 – 2 ^ 7
~
2 7 1 2 ^ 7-1
Character \u0000 ~ \u007F
Short
2 7 – 2 ^ 7
~
2 7 1 2 ^ 7-1
Integer
2 7 – 2 ^ 7
~
2 7 1 2 ^ 7-1
Boolean true & false

2. String String

2.1 define

public final class String implements java.io.Serializable.Comparable<String>, CharSequence {
    /** The value is used for character storage. */
    private final char value[];
}
Copy the code

The code above is the definition of String in Java 8. The underlying code actually uses an array of char, and since it is declared final, that means it cannot be inherited. And once initialized, no other array can be referenced. This ensures that strings are immutable and thus thread-safe.

2.2 Advantages of immutability

  1. Used to cachehash

Since the hash value of String is used frequently, its immutability makes the hash value immutable, requiring only one calculation.

  1. The String constant Pool (String Pool) is required

If a String has already been created, references to it are first fetched from the String constant pool. Immutability ensures that different references refer to the same String.

  1. security

We often use String as an argument to our method, which is immutable to ensure that the argument is immutable;

  1. Thread safety

The immutability of String makes it inherently thread-safe and can be easily used across multiple threads without regard to thread-safety issues.

2.3 String vs StringBuffer vs StringBuffer

The three are compared mainly from three aspects:

variability Thread safety Applicable scenario
String immutable security Manipulating small amounts of data
StringBuffer variable Safe, for internal usesynchronizedTo synchronize Multithreading manipulates large amounts of data in string buffers
StringBuilder variable unsafe Single thread operation string buffer manipulation of large amounts of data, performance is higher thanStringBuffer

2.4 String Constant Pool (String Pool)

The String Pool, located in the method area, typically holds all of the literal strings that are determined at compile time. Alternatively, it can be added to the String Pool at run time using the intern() method in String. When a String calls intern(), a reference to the String Pool is returned if a String Pool already has the same literal value. If not, add a new String to the String Pool and return a reference to the new String;

String s1 = new String("aaa");
String s2 = new String("aaa");
// false Two strings point to different objects
System.out.println(s1 == s2);   

String s3 = s1.intern();
String s4 = s1.intern();
// if there is a string with the same literal value in the constant pool, fetch it directly
System.out.println(s3 == s4);
Copy the code

In the following code, memory analysis is shown as follows:

String str1 = "Village Rain Yao";
String str2 = "Village Rain Yao";
String str3 = new String("Village Rain Yao");
String str4 = new String("Village Rain Yao");

// true, both references point to the same object in the constant pool
System.out.println(str1 == str2);
// false, two references to different objects in the heap
System.out.println(str3 == str4);
Copy the code

2.5 the new String (” XXX “)

When you create a string object using new, there are two different situations:

  1. String Pool does not have “XXX”

Two String objects are created. “XXX” is a String literal, so at compile time a String object is created in the String Pool that refers to the String literal “XXX”. New then creates a string object in the heap;

  1. “XXX” exists in String Pool

In this case, you only need to create a String object. Since there is already an object pointing to “XXX” in the String Pool, you can create a String object directly in the heap.

3. Basic grammar

3.1 annotations

  • Single-line comments
// This is a one-line comment
String name = "Village Rain Yao";
Copy the code
  • Multiline comment
/* * this is a multi-line comment * name, public number */
String name = "Village Rain Yao";
Copy the code
  • Documentation comments
/ * * *@author: Village yu Yao *@param: name, public id */
String name = "Village Rain Yao";
Copy the code

3.2 Common Keywords

3.3 Identifiers and Keywords

  • Identifiers: Used to name programs, classes, objects, variables, methods, interfaces, custom data types, etc.
  • Keywords: special identifiers that have been assigned special meanings by Java and can only be used for specific purposes;
  • Naming rules for identifiers(Refer to the “Alibaba Development Manual”, pay attention to the public number [Village, the rain awayDownload PDF)
    1. Identifiers are lowercase characters (A-Z, A-Z), digits (0-9), and underscores (_)._) and dollar sign ($);
    2. It cannot start with a number or be a keyword.
    3. Strictly case sensitive;
    4. Package name: multiple words are all lowercase words;
    5. Class names and interfaces: capital camel case nomenclature;
    6. Variable names and function names: When multiple words are used, the first word is all lowercase and all other words use the capital camel name.
    7. Constant names: all uppercase letters with underscores between words (_) segmentation;

3.4 Access control characters

scope The current class The samepackageThe class of A subclass otherpackageThe class of
public 😀 😀 😀 😀
protected 😀 😀 😀 😡
default 😀 😀 😡 😡
private 😀 😡 😡 😡

3.5 Static, final, this, super

  1. static

Static can be used in the following 4 scenarios:

  • Decorates member variables and member methods:staticThe decorated members belong to the class, are static member variables, and are stored in Java memoryMethods area, does not belong to a single object, is shared by all objects, and is best passedStatic member name/static method name ()Call;
  • Static code blocks: defined outside of a method in a class, executed before non-static code blocks (static code blocks -> non-static code blocks -> constructors) and executed only once, no matter how many times the operation to create a new object is performed;
  • Static inner class: Static is the only way to modify a class. A non-static inner class implicitly stores a reference to the external class that created it after compilation, but a static inner class does not exist. The inner class can only use static member variables and methods from any of the outer classes.
  • Static guide package: used to import static resources,import staticUsed to specify the static resources in a class to be imported, and then we can directly use the static member variables and methods in the class;
  • Note:
    • abstractMethods can’t both bestaticBecause theabstractThe method needs to be rewritten, butstaticMethod does not;
    • Not fromstaticCalls to non-static methods are issued from within a method because static methods can only access static members, whereas non-static method calls require object creation first;
    • staticCannot be used to modify local variables;
    • The difference between inner and static inner classes: a static inner class is independent of an outer class, and the variables and methods in the outer class cannot be accessed directly from the static inner class. If access is requirednewAn external class object that can be accessed, but can be called directly for static variables and methods. A normal inner class exists as a member of the outer class, and can directly access the attributes and call the methods of the outer class.
  1. final
  • When modifying a class, the class cannot be inherited, and all member methods of the class are implicitly specified as final methods;
  • When modifying a method, it indicates that the method cannot be overridden.
  • When you modify a variable, the variable is a constant. If the variable is a basic data type, it cannot be changed after initialization. If the variable is a reference type, it cannot point to any other object after initialization.
  1. this

Used to refer to the current instance of a class, as in our most common constructor.

public class User{
    int age;
    
    public User(int age){
        this.age = age; }}Copy the code

Where this.age indicates that a member variable of the User class is accessed, followed by age, which represents the parameter passed in.

  1. super

Use to access variables and methods in a parent class from a subclass.

public class Father{
    String name;
    
    public Father(String name){
        this.name = name;
    }
    
    public Father(a){}}Copy the code
public class Son extends Father{
    public Son(String name){
        super(a);this.name = name + ".jr"; }}Copy the code

3.6 Continue, Break, and Return

The keyword instructions
continue Used of loop construction to jump out of the current loop and into the next loop
break Used of a loop structure to jump out of the loop and continue executing the statements below the loop
return 1. return ;Direct use:returnEnd method execution, for methods that do not return a value function;

2. return value;return A specific value for a method that has a return value function

3.7 While Loops and DO loops

The while loop structure determines whether the next iteration should continue before the loop begins, and may not execute at all.

The do… While determines whether to continue the next iteration at the result of the loop, executing the body of the loop at least once;

3.8 Final, finally, Finalize

  1. final

Final is both a modifier and a keyword, and can mean different things when modifying different objects.

  • Modifier class: indicates that the class cannot be inherited;
  • Modifying variables: If a variable is a basic data type, its value cannot be changed after initialization. If a variable is a reference type, it cannot be made to point to another object after initialization, but the content of the object it points to is mutable.
  • Modification methods: indicates that the method cannot be overridden, but overloads are allowed,privateThe method is implicitly specified asfinalMethods;
  1. finally
  • finallyIs a keyword that is provided during exception handlingfinallyBlock to perform any cleanup operation, whether or not an exception was thrown or caught,finallyBlocks are executed, usually to free resources;
  • finallyIt must be executed under normal circumstances, but it will not be executed under the following two conditions:
    • The correspondingtryIf the command is not executed, thetryThe blockfinallyBlocks are not executed;
    • iftryBlock JVM shutdown, thenfinallyBlocks don’t execute either;
  • finallyIf you have inreturnStatement, overwritestrycatchIn thereturnStatement, causing both to failreturn, so it is suggested thatfinallyDo not exist inreturnKey words;
  1. finallize

Finallize () is a protected method of Object that subclasses can override for resource cleanup;

GC will call this method before collection, but Finalize () method has the following problems:

  • The Java language specification is not guaranteedfinalize()Methods are executed in a timely manner, and there is no guarantee that they will be executed;
  • finalize()Methods can cause performance problems because the JVM typically completes in a separate low-priority threadfinalizeThe implementation;
  • finalize()Method, you can assign the object to be reclaimed toGC RootsReachable object references to achieve object regeneration;
  • finalize()Method is executed by GC at most once (but you can call the object’s manuallyfinalizeMethods);

4. Operator

4.1 Arithmetic Operation

The operator describe example
+ Addition – The values on both sides of the addition operator A plus B is equal to 30
- Subtraction – the left operand minus the right operand A minus B is equal to minus 10
* The values on both sides of the multiplication-multiplication operator A times B is equal to 200
/ Division – Left operand divided by right operand B/A is equal to 2
% Mod – The remainder of the left operand divided by the right operand B % is equal to 0
++ Increment: Increases the value of the operand by 1 B++ or ++B is equal to 21
-- Decrement: Decreases the value of the operand by 1 B– or B is equal to 19

Note: ++ and — can be placed before or after operands; If it precedes the operand, it increments/subtracts first and then assigns. After the operand, the value is assigned and then incremented/subtracted; So the sum up is that the sign goes before plus and minus, the sign goes after plus and minus.

4.2 Relational operators

The operator describe example
= = Checks if the values of the two operands are equal, and if they are equal the condition is true. False (A == B).
! = Checks if the values of the two operands are equal, and the condition is true if the values are not. (A ! = B) true.
> Checks whether the value of the left-hand operand is greater than the value of the right-hand operand, if so, the condition is true. (A> B)
< Check whether the value of the left-hand operand is less than the value of the right-hand operand, if so, the condition is true. A <B is true.
> = Checks whether the value of the left-hand operand is greater than or equal to the value of the right-hand operand, if so, the condition is true. (A> = B)
< = Checks whether the value of the left-hand operand is less than or equal to the value of the right-hand operand, if so, the condition is true. (A <= B) is true.

4.3 bit operator

The operator describe example
& If both corresponding bits are 1, the result is 1; otherwise, it is 0 A&B, you get 12, which is 0000, 1100
` ` If both corresponding bits are 0, the result is 0; otherwise, it is 1
^ The result is 0 if the corresponding bit values are the same, 1 otherwise A to the B is 49, which is 0011, 0001
~ The bitwise inverse operator flips each bit of the operand, that is, 0 becomes 1, and 1 becomes 0. (A) is minus 61, which is 1100, 0011
<< Bitwise left shift operator. The left operand moves the right operand by bits to the left. A << 2 is 240, which is 1111 0000
>> Bitwise right shift operator. The left operand moves right by bit to the number of digits specified by the right operand. A >> 2 gets 15 which is 1111
>>> Bitwise right shift zeroing operator. The value of the left-hand operand moves to the right by the number of digits specified by the right-hand operand, and the resulting space is filled with zeros. A>>>2 gets 15 which is 0000 1111

4.4 Logical operators

The operator describe example
&& Called logic and operators. The condition is true if and only if both operands are true. (A && B)Is false.
` ` Called logic or operators. If either of the operands is true, the condition is true.
! This is called a logical non-operator. Used to reverse the logical state of operands. If the condition is true, the logical non-operator will get false. ! (A && B)Is true.

4.5 Assignment operators

The operator describe example
= Simple assignment operator that assigns the value of the right-hand operand to the left-hand operand C = A + B will assign the value of A + B to C
+ = The addition and assignment operator assigns the left-hand operand to the left-hand operand by adding the left-hand and right-hand operand C plus A is the same thing as C is equal to C plus A
- = The subtraction and assignment operator, which assigns the subtraction from the left-hand operand to the left-hand operand C minus A is the same thing as C minus A
* = The multiplication and assignment operator assigns the left-hand operand to the left-hand operand by multiplying the left-hand and right-hand operand C times A is the same thing as C times A
/ = The division and assignment operator assigns the left-hand operand to the left-hand operand by dividing the right-hand operand C / = A, C and A are of the same type is equivalent to C = C/A
% = The modulo and assignment operator, which modulo the left-hand and right-hand operands to the left-hand operand C % = A is the same thing as C = C % A
< < = The left shift assignment operator C << = 2 is equivalent to C = C << 2
> > = The right shift assignment operator C >> = 2 is equivalent to C = C >> 2
& = Bitwise and assignment operators C squared is the same thing as C squared
^ = Bitwise xor assignment operator C ^ 2 is the same thing as C ^ 2
` = ` Bitwise or assignment operators

4.6 Conditional operators (? 🙂

Also known as the ternary operator, has three operands and needs to determine the value of a Boolean expression;

variable x = (expression) ? value if true : value if false
Copy the code

4.7 instanceof

Used to manipulate object instances and check whether the object is of a specific type (class type or interface type);

( Object reference variable ) instanceof  (class/interface type)
Copy the code

4.8 the equals () and = =

  • = =

Basic data types compare values with ==, which is used to determine whether the memory address of two objects is equal when referencing data types, that is, whether two objects are the same object.

Essentially, since only value is passed in Java, both primitive data types and reference data types compare values, except that reference type variables hold the address of the object.

  • equals()

It is also used to determine whether two objects are equal, but cannot be used to compare primitive data type variables. Equals () exists in the Object() class, so all classes have equals(). There are two uses:

  1. Class not coveredequals()methods: Pass at this timeequals()When comparing two objects of this class, equivalent to= =Compare the two objects, used by defaultObjectIn the classequals()Methods;
  2. Class coversequals()methodsOnce overridden, this method is used to compare the contents of two objects for equality, as we often doString, BitSet, Data, FileIt covers aequals()Methods;

Method 5.

5.1 Types of methods

  1. No parameter, no return value;
  2. Return value with no parameter;
  3. No return value with parameters;
  4. There are parameters and return values;

5.2 Overloading and Rewriting

  1. “Overload”

Overloading is the ability for the same method to do different things depending on the input. Overloading occurs at compile time, and within the same class, the method name must be the same, the parameter type, the number of arguments, the order of arguments, and the return value and access modifier can be different. In summary: Overloading is when multiple methods of the same name in the same class perform different logical processing based on different arguments.

  1. Override

Overrides are when a subclass inherits the same method from the parent class, with the same input data, but with a different final response than the parent class. Overrides occur at run time, when subclasses overwrite the implementation logic of methods that their parent classes allow access to. Overriding methods must have the same method name, argument list, and return value, throw exceptions within the scope of the parent class, and access modifiers within the scope of the parent class. In addition, if the parent class method does not have private/final/static modification, the child class cannot override the parent class method, but the static modified method can be declared again. The constructor is a special case and cannot be overridden. To sum up: overrides are subclasses that modify their parent methods so that they cannot change the external appearance, but can change the internal logic.

  1. Reloading vs rewriting
The difference between overloading rewrite
The list of parameters Must be different Must be the same
The return type Can be different Must be the same
Access modifier Can be different Can’t be more strict than the parent class
In scope In the same class Father and son class
Abnormal range Can be modified Can be reduced or deleted, cannot throw new exceptions or more extensive exceptions
Stage of development Compile time The run-time

5.3 Deep/Shallow Copy

  1. Shallow copy

A shallow copy is a bitwise copy of an object that creates a new object with an exact copy of the original object’s property values. If the property is of a primitive type, the value of the primitive type is copied. If the property is a reference type (memory address), the memory address is copied. Therefore, if either object changes the reference type attribute, it affects the other;

  1. Deep copy

Deep copy copies all attributes and dynamically allocated memory to which the attributes point. Deep copying occurs when an object is copied along with the object it references. Deep copying is slower and more expensive than shallow copying.

  1. conclusion

After a shallow copy, changing one of the values will cause the other to change. However, after the deep copy, changing any one value does not affect the other value.

5.4 value transfer

Recommended reading: juejin. Im /post/5bce68…

5.4.1 Parameters and arguments

  1. parameter: arguments to be passed in when the method is called, such asfunc(String name)In thenameIs a parameter, only infuncIs callednameWhen the method is finished executing,nameWill automatically destroy free space;
  2. Argument: the actual value passed in when a method is called, initialized before the method is called and passed in when the method is called;
public static void func(String name){
    System.out.println(name);
}

public static void main(String[] args) {
    / / arguments
    String name = "Village Rain Yao";
    func(name);
}
Copy the code

5.4.2 Value Passing and Reference Passing

  1. Value passed

When a method is called, the argument is passed a copy of its content into the method via the parameter. The content received by the parameter is actually a copy of the argument, so any operation on the parameter within the method is only on the copy of the argument and does not affect the content of the original value of the argument. That is, the value is passed a copy of the argument, and operations on the copy do not affect the original value of the argument, that is, no matter how the parameter changes, the content of the argument is not affected.

public static void valueCrossTest(int age,float weight){
    System.out.println("Passed age:"+age);
    System.out.println("Weight passed in:"+weight);
    age=33;
    weight=89.5 f;
    System.out.println("Method age after reassignment:"+age);
    System.out.println("Reassigned weight within the method:"+weight); 
}

public static void main(String[] args) {
    int a=25;
    float w=77.5 f;
    valueCrossTest(a,w);

    // a = 25, the original value is not affected
    System.out.println(Age after method execution:+a);
    // w = 77.5
    System.out.println("Weight after method execution:"+w)
}
Copy the code
  1. reference

When a method is called, the address of the argument is passed to the corresponding parameter. Inside the method body, the parameter and the argument point to the same address memory, so manipulating the parameter affects the actual content of the argument.

But reference passing does not exist in Java, because when an argument is passed to a parameter, for both primitive and reference types, it is passed by value, that is, a copy of the argument is passed, not the content of the argument itself.

  1. conclusion

If you operate on data of a primitive data type, the original content of the argument is not affected because both the original content and the copy of the argument store the actual value and are on different stacks.

If you are operating on data of reference type, there are two cases,

  • One is that the parameter and the argument point to the same object address, so the operation of the parameter affects the content of the object to which the argument points.
public static void PersonCrossTest(Person person){
    System.out.println("Name of person passed in:" + person.getName());
    person.setName("I'm Zhang Xiaolong.");
    System.out.println("Method name after reassignment:" + person.getName());
}
Copy the code
  • If the parameter is changed to a new object address (such as reassigning a reference), the operation of the parameter does not affect the content of the object to which the argument points.
public static void PersonCrossTest(Person person){
    System.out.println("Name of person passed in:" + person.getName());
    person=new Person();
    person.setName("I'm Zhang Xiaolong.");
    System.out.println("Method name after reassignment:" + person.getName());
}
Copy the code

6. Object oriented

6.1 Object-oriented vs. procedural

Recommended reading: www.zhihu.com/question/27…

  • Object Oriented

Process-oriented is an approach to understanding and abstracting the real world, which is easier to maintain, reuse, and extend. The most important characteristics are inheritance, encapsulation, polymorphism, so the design of the system coupling is low, but the performance is lower than process oriented.

  • Procedure Oriented

Process-oriented is a process-centric approach to programming that focuses on what is happening, as opposed to who is affected. The main difference lies in encapsulation, inheritance, polymorphism, its performance is higher than object-oriented.

  • conclusion

The object-oriented approach allows each class to do its job and eventually come together to complete a project, while the process-oriented approach allows more and more functionality in a class, like a full-stack engineer who can do everything by himself.

6.2 Encapsulation, inheritance, polymorphism

  1. encapsulation

The objective things are encapsulated as abstract classes, and classes can only operate their data and methods for trusted classes or objects, and hide information for untrusted classes. That is, the commonality of things belonging to the same class (attributes and methods) into a class, so that it is easy to use.

Through encapsulation, the division of specialization is realized, and the code that can achieve a specific function is encapsulated as an independent entity for us to call when we need. In addition, encapsulation hides information as well as implementation details, allowing us to hide information we want to hide with access permissions.

  1. inheritance

You can use all the functionality of an existing class without having to rewrite the existing class to extend the functionality, that is, personality accepts common attributes and methods and adds attributes and methods unique to the feature. The new class that is inherited is called a subclass/derived class, and the inherited class is called a parent class/base class/superclass and has the following characteristics:

  • The subclass has all the attributes and methods of the object of the parent class, but the private attributes and methods of the parent class cannot be accessed by the subclass.
  • A subclass can extend a parent class;
  • Subclasses can implement methods of their parent class in their own way;
  1. polymorphism

Polymorphism is a technique that allows a parent object to be set equal to one or more of its children. Once assigned, the parent object can behave differently depending on the characteristics of the pointing subclass object. That is, the parent class refers to the subclass object instance and can be overridden or overridden. It has the following characteristics:

  • Object types are immutable, but reference types are mutable;
  • There is an inheritance (class)/implementation (interface) relationship between object types and reference types;
  • Methods are polymorphic, but attributes are not.
  • If a subclass overrides a superclass method, then the method overridden by the subclass is actually executed. If the subclass does not override a superclass method, then the superclass method is called.

6.3 Member variables vs local variables vs static variables

different grammar Storage location The life cycle The initialization value Call way The alias
Member variables 1. Belong to class

2, can be access to the control character,The static and finalSuch modification
The heap Live or die with the object Yes, the basic data type is the default value, and the object is the default valuenull The object The instance variables
A local variable 1. Belong to a method (a variable or parameter in a method)

2. Cannot be accessed by the control character andstaticEmbellish, but can befinalmodified
The stack Live or die with the method None. You must define and assign a value before using it
A static variable 1. Belong to class

2,staticModifier, shared by all class objects
Methods area Live or die with the class Initializes the value of a member variable Class name call (recommended), object call Class variables

6.4 Characteristics of the construction method

  1. The method name is the same as the class name;
  2. No return value, but cannot be usedvoidKeyword declaration;
  3. Automatically executed when class objects are generated without explicit call;

6.5 Abstract Classes & Interfaces

  1. interface
  • All methods in the interface default to public and have no implementation (prior to Java 8, Java 8 began to have default implementations);

  • All variables in the interface are static and final, and no other variables are allowed.

  • A class can implement multiple interfaces (through the implements keyword), and the interface itself can extend multiple interfaces through extends;

  • Interface is the abstraction of behavior and belongs to the behavior norm.

  1. An abstract class
  • Abstract classes can have both abstract methods and non-abstract methods.
  • A class can only implement one abstract class;
  • Abstract methods can bePublic, protected, defaultModify, but not useprivate, otherwise cannot be overwritten;
  • Abstract is the abstraction of class, is a template design;

6.6 Common Methods in the Object Class

methods instructions
public final native Class<? > getClass() The Class object used to return the current runtime object is modified with the final keyword, so subclass overrides are not allowed
public native int hashCode() The hash code used to return an object, primarily in hash tables such as the HashMap in the JDK
public boolean equals(Object obj) The String class overrides the method used to compare the memory addresses of two objects. The user compares the values of strings
protected native Object clone() throws CloneNotSupportedException Used to create and return a shallow copy of the current object. In general, for any object x, the expression x.lone ()! = x is true, x.lone ().getClass() == x.gottclass () is true. Object does not implement the Cloneable interface, so don’t rewrite the clone method and call CloneNotSupportedException abnormal happens
public String toString() Returns a hexadecimal string of the class name @ hash code of the instance. It is recommended that all subclasses of Object override this method
public final native void notify() You can’t rewrite it. Wakes up a thread waiting on the monitor of this object (the monitor is equivalent to a lock). If there are multiple threads waiting, only one will wake up randomly
public final native void notifyAll() You can’t rewrite it. As with Notify, the only difference is that all threads waiting on this object’s monitor are woken up instead of one thread
public final native void wait(long timeout) throws InterruptedException You can’t rewrite it. Note that the sleep method does not release the lock, while the wait method releases the lock. Timeout is the waiting time. After calling this method, the current thread goes to sleep until the following time occurs:

1. Other threads call the objectnotify()/notifyAll()Methods;

2. The time interval is up.

3. Another thread calledinterrupt()Interrupt the thread;
public final void wait(long timeout, int nanos) throws InterruptedException Added the Nanos parameter, which represents extra time (in nanoseconds, ranging from 0 to 999999). So you have to add nanos milliseconds to the timeout
public final void wait() throws InterruptedException This is the same as the previous two wait methods, except that this method keeps waiting without the concept of a timeout
protected void finalize() throws Throwable { } The action triggered when the instance is collected by the garbage collector

HashCode & equals 6.7

Recommended reading: juejin. Im /post/5a4379…

6.7.1 equals

  1. rewriteequals()Criteria of the method:
guidelines instructions
reflexivity To any non-null reference valuex.x.equals(x)Should be returnedtrue
symmetry For any non-null reference valuex andywheny.equals(x)returntrue When,x.equals(y)Also should returntrue
transitivity For any non-null reference valueX, y,zIf thex.equals(y)returntrueAnd,y.equals(z)returntrue, thenx.equals(z) Also should returntrue
consistency For any non-null reference valuex y, multiple callsx.equals(y)Always returntrueOr always returnfalseThe premise is on the objectequals The information used in the comparison was not modified
Non empty For any non-null reference valuex.x.equals(null)Should be returnedfalse

6.7.2 hashCode

HashCode is used to return the hash value of an Object, mainly to speed up lookups. Since hashCode() is a method in the Object class, all Java classes have hashCode(), In hash structures such as HashTable and HashMap, hashCode() is used to find the position in the HashTable, and hashCode can be used to fast small memory blocks of tea ceremony.

6.7.3 Why should I Rewrite this documentequals()Must be rewrittenhashCode()

  1. If two objects are equal, thenhashCode()It must be the same becauseequals()Is infallible;
  2. If two objects are equal, they are called separatelyequals()The method also returnstrue;
  3. Two objects have the samehashCode()They are not necessarily equal becausehashCode()Not infallible;
  4. If I rewrite itequals(), but keephashCode()The implementation of is unchanged, then it may appear that the two are equal, buthashCodeBut not the same;
  5. So once you rewrite itequals()Method must be overriddenhashCode().hashCode() The default behavior is to generate unique values for objects on the heap. If I didn’t rewrite ithashCode(), then theclassAre never equal in any case (even if the two objects point to the same data).

6.8 Serialization and deserialization

6.8.1 definition

  • Serialization: The process of converting an object into a sequence of bytes;
  • Deserialization: The process of converting a sequence of bytes into a target object;

6.8.2 Serialization Scenarios

When A Java object needs to be transferred over the network or persisted to a file, we need the object to be serialized.

6.8.3 How to Implement serialization

To implement serialization, you simply have the class implement the Serializable interface, and the class can be serialized.

If you do not want to serialize some data in a class, you can use the transient keyword, for example:

// Pass the keyword TRANSIENT to indicate that serialization is not involved
transient private String telephone;
Copy the code