Q & a summary of javase basic knowledge (common sense concept + basic grammar)

BWH_ Steven 2021-01-22 13:58:11
summary javase basic knowledge common


Let me write it first

This project is from 20 Set up at the end of the year flag, After several years of study , Looking back at many knowledge points, I have a new understanding . So take advantage of the internship preparation , Combined with previous learning reserves , Create a program for new students and beginners Java Open source knowledge projects , focus Java Back end interview questions + analysis + Detailed explanation of key knowledge + Open source projects with selected articles , I hope it can accompany you and I have been improving !

explain : I really have a lot of heart in this project , All the content is that I refer to many bloggers ( The source has been indicated ), Information ,N books , And combined with their own understanding , Redrawing , Reorganize the language and so on . The power of the individual is weak , Or there may be shortcomings , Be unavoidable , But update / The improvement will go on all the time . Every one of you Star It's all my encouragement ! I hope you like it .

notes : All the pictures involved do not use the network chart bed , Articles are open source for you .

Project name : Java-Ideal-Interview

Github Address : Java-Ideal-Interview - Github

Gitee Address :Java-Ideal-Interview - Gitee( Code cloud )

Ongoing update , Online reading will be available later , If you think Gitee or Github It's not easy to read , It can be cloned locally Typora Wait for the editor to read

if Github Cloning is too slow , You can choose to use domestic Gitee Warehouse

notes : This article mainly contains Java Basic knowledge of (Java Introduction to common sense concepts + Basic grammar )

  • object-oriented , Collection and so on The following will be updated in batches according to the plan

One Java Basic knowledge of

1. Common sense of concept

1.1 Please talk about your right to JVM JDK JRE To know and understand

1.1.1 JVM(Java Virtual Machine)

JVM Also known as Java virtual machine , Used to run Java Bytecode file (.class), because JVM For a particular system (Windows,Linux,macOS) There are different implementations , That is, it shields the specific operating system and platform information , Therefore, the same bytecode file can run on any platform , And get the same result .

1.1.1.1 What is bytecode ?

extension .class This file is called bytecode , It's a low-level representation of a program , It does not target any specific processor , Virtual machine only (JVM), After virtual machine processing , Can make the program run on multiple platforms .

1.1.1.2 What are the advantages of bytecode ?

Java Language by bytecode , To some extent, it solves the problem of low efficiency of traditional interpretative languages , At the same time, it retains the characteristics of transplantable explanatory language . therefore Java Programs run more efficiently , and , Because bytecode is not specific to a particular machine , therefore ,Java The program can run on many different computers without recompilation .

Why does it solve the problem of low efficiency of traditional interpretive language to some extent ( Think about it - scherman , For reference only )

First of all, two things ,① because Java Bytecode is pseudo machine code , So it's more efficient than analytic languages ②JVM It's not an analytic language , It's a semi compiled and semi analytic language

Analytic languages have no compilation process , Is to parse the source code text directly , It is equivalent to a compilation at execution time , and Java Although the bytecode of can't exactly correspond to the local machine code one by one , But it can be simply mapped to local machine code , You don't need to do complicated parsing and other compilation processing , Faster than pure analytic languages, of course .

1.1.2 JRE(Java Runtime Environment)

JRE yes Java Runtime environment , It contains JVM and Java Some basic class libraries of , It's used to run the compiled Java Program ( It's used to run , Can't create a new program )

1.1.3 JDK(Java Development Kit)

JDK yes Java Development kit , It's programmers who use Java Language development Java The necessary toolkit for the program , It's not just about JRE , It also includes compiler (javac) There's a lot more java debugging , analysis , Document related tools . Use JDK You can create and compile programs .

1.1.3.1 Just for Java Running environment JRE, It is necessary to install JDK Do you

Just to run a Java Program ,JRE It's totally enough , But words can't be so absolute

Sometimes , Even if you don't plan to do anything on the computer Java Development , Still need to install JDK. for example , If you want to use JSP Deploy Web Applications , So technically , You're just running on the application server Java Program . Then why do you need to JDK Well ? Because the application server will JSP Convert to Java servlet, And need to use JDK To compile the servlet.( Reference from Github- JavaGuide , For reference only )

therefore , Most of the time, install JDK Still necessary , It needs to be decided on a case by case basis .

1.1.3.2 You can talk about Java Is it a process from code to run ?

The process : To write -> compile -> explain ( This is also Java Why compilation and interpretation coexist )

First, through IDE/ Editor to write the source code, and then through JDK Compiler in (javac) Translate it into Java Bytecode file (.class file ), Bytecode is executed through a virtual machine , The virtual machine sends each bytecode to be executed to the interpreter , The interpreter translates it into machine code on a particular machine ( And its executable binary machine code ).

1.2 Please compare Java And JavaScript 、C++

1.2.1 Java And JavaScript

  • Different uses :Java It is widely used in the development of Internet applications . and JavaScript Mainly embedded in Web Page , For reading and writing HTML, control cookies etc. .
  • Positioning is different :Java It's object-based , Simple development also requires designing and creating classes . and JavaScript This scripting language is object-based and event driven , It can achieve various functions by providing a large number of good internal objects .
  • Code execution is different :Java Source code will be compiled into bytecode files , then JVM Distribute the bytecode file to the interpreter for interpretation , Therefore, it belongs to the coexistence of compilation and interpretation . and JavaScript It's an explanatory language , The source code doesn't need to be compiled , The browser can interpret and execute ( JIT ( Just in time compilation ) Can improve JavaScript Operating efficiency ).
  • Different types of data :Java Use strong type checking , Before compiling, you must declare , and JavaScript Weak type , Even variables can not be declared before use ,JavaScript Check at run time to infer its data type .

1.2.2 Java And C++

  • The pointer :Java The language does not explicitly provide a pointer to the user to access memory , Added automatic memory management , It can be avoided in C/C++ The problem of wild pointer caused by misoperation in , Make the program more secure ( It just doesn't offer , It's not that there are no pointers , Pointers are still used internally in the virtual machine, but they are not provided externally ).
  • Inherit :Java The classes of are single inheritance , and C++ But it can be inherited multiple times , but Java By inheritance / Implement multiple interfaces .
  • memory management : Java Of JVM There's one of them GC Mechanism ( Garbage collection mechanism ), There is no need for the programmer to manually release unused memory
  • Operator overloading :Java Operator overloading is not allowed , and C++ Then you can .

2. Basic grammar

explain : This section includes : keyword , identifier , notes , Constant , Variable , Operator , Branch , The relevant contents of the cycle .

data type 、 The methods are arranged separately as The first 3 Bigger and The first 4 Bigger

2.1 The difference between identifier and keyword

The essence of identifier and keyword is a name , For example, class name , Method name , Variable name ... , And keywords , It's a special identifier , It has a special meaning , for example public return try catch ... , Because keywords have their specific location and purpose , So common identifiers are not allowed to have the same name as keywords .

2.2 Java Common naming rules ( Nonstandard )

notes : As described below , All are hard rules of naming , Not recommended specifications , For details, please refer to 《 Alibaba Java Development Manual 》

basic :

  • Package name : All lowercase with . separate eg: com.baidu.www ( Domain name write back )
  • Class name / Interface : title case , Multiple words are named after humps
  • Method or variable name : Initial lowercase , Multiple words are named after humps
  • Constant names : All capitals , use _ separate

identifier :

  • First character : Letter (A-Z、a-z)、 Dollar symbol ($)、 Underline (_
  • After the first character : Letter (A-Z、a-z)、 Dollar symbol ($)、 Underline (_) Or any character combination of numbers

2.3 Types of notes

There are three kinds of annotations :① Single-line comments (// The comment )、② Multiline comment (/* The comment */)、③ Documentation Comments (/** The comment */

2.3.1 What do you think of the annotation specification

First of all, the function of annotation :① Can accurately reflect the design ideas and code logic ② Be able to describe the meaning of business

A good note , After a long period of time , Help you quickly recall your thoughts at that time , It can also help new people who receive this code , Get a quick idea of what you're thinking .

Code comments are not as detailed as possible . In fact, good code itself is a comment , We should try our best to standardize and beautify our code to reduce unnecessary comments . If the programming language is expressive enough , There's no need to comment , Try to explain it in code .—— 《Clean Code》

2.4 The difference between character constants and string constants

  • In different forms : A character constant is a character caused by a single quotation mark , And string constants are caused by double quotes 0 One or more characters
  • Meaning is different : A character constant is equivalent to an integer value ( ASCII value ), Can participate in expression operation , And the string constant represents an address value ( The string is stored in memory )
  • The memory size is different : Character constants only take up 2 Bytes ( char stay Java Two bytes in ), String constant takes several bytes

2.5 char Type variable can store a Chinese character ?

char Type variables are used to store Unicode Of encoded characters , and Unicode The coded character set contains Chinese characters , therefore ,char Of course, Chinese characters can be stored in type variables . If a special Chinese character is not included in unicode Coded character set , that , This char This special Chinese character cannot be stored in the type variable .

Additional explanation :unicode Encoding takes two bytes , therefore ,char Variable of type also takes two bytes

2.6 final What is the function of keywords

  • final Modified classes cannot be inherited ,final The member variables in a class can be set to... As needed final, But should pay attention to final All member methods in a class are implicitly specified as final Method .
  • final Methods that modify cannot be overridden
  • final The variable decorated is called a constant , If it's a basic type , The value cannot be changed after initialization , If it's a reference type , After initialization, it can no longer point to another object .

2.7 Pre or post auto increment / The difference between self subtraction operators

++ and -- It's just self increasing variables 1 Or self reducing 1 Operator , There is a difference between pre and post :

The rules : Operators are preceded by / reduce , The operator is followed by / reduce

int x = 4;
int y = (x++) + (++x) + (x * 10);
System.out.println(y);

First (x++) in x After ++ So after adding and subtracting , namely x When calculating, take 4 And then increase to 5

secondly (++x) in x In front of ++ So add and subtract first , x = 6

next x 10 = 6 10 = 60

Finally, execute the assignment statement , namely :y = 4 + 6 + 60 = 70

2.8 & and && The difference between

& There are two uses of operators :① Bitwise AND ② Logic and ( This is only about )

&& Operators are short circuit and operation

Logic and short-circuit and both require that the Boolean values on both sides of the operator are true The value of the entire expression is true

&& It has the function of short circuit , If && The value of the expression on the left is false, The expression on the right will be short circuited directly , No arithmetic , So it's more efficient

Generally, it is recommended to use &&, For example, when verifying the user login, determine that the user name is not null And it's not an empty string , It should be written as :username != null &&!username.equals(""), The order of the two cannot be exchanged , Not to mention & Operator , Because if the first condition doesn't hold , No strings at all equals Compare , Otherwise, it will occur NullPointerException abnormal .

Be careful : Logical or operator (|) And short circuit or operator (||) The same is true of the difference between the two .

Add :& It can also be used as a bit operator , When & When the result of operands or expressions on both sides is not Boolean ,& That is, operate according to the operator

2.9 There are several ways to exchange the values of two integers ?

The way 1: Use an intermediate value to pass ( Because of its high readability , So this method is also commonly used in development )

The way 2: Implement with XOR

  • ^ The character of XOR operator : One data to another data bit exclusive or twice , The number itself does not change
a = a ^ b;
b = a ^ b; // take a Into the , namely : b = a ^ b ^ b
a = a ^ b; // a still a ^ b , b Turned into a namely : a = a ^ b ^ a = b

The way 3: The method of adding variables

a = a + b;
b = a - b;
a = a - b; 

The way 4: In a word

b = (a + b) - (a = b);

In this way 1 2 4 It's easy to understand , By the way, I want to review the original inverse complement , And all kinds of bit operations

2.9.1 Let's talk about the original code , Complement code , Inverse code

In the computer , There are three representations of signed numbers , Source code 、 Inverse code 、 And complement . And all the data operations are carried out by complement code

  • Original code : Binary point representation , The highest bit is the sign bit ,“0” Express positive ,“1” Negative , The rest of the positions indicate the size of the value , It can directly reflect the size of the data .

    • What is the highest bit of the original code of a positive number 0 , The highest bit of the original code of a negative number is 1 , The others are numerical bits
  • Inverse code : Solve the problem of negative addition , Convert subtraction to addition , So as to simplify the operation rules .

    • The inverse of a positive number is the same as the original , The inverse of a negative number is the same as the sign bit of the source code , Reverse the value bit 1 -> 0 、 0 -> 1
  • Complement code : Solve the problem of positive and negative zeros in the addition of negative numbers , It makes up for the lack of inverse code .

    • The complement of a positive number is the same as the original code , The complement of a negative number is based on the inverse +1

2.9.2 Introduce several bit operations

Bit operations need to convert data into binary , use 0 Make up the number of digits

& Bit and operator : Yes 0 be 0

| Bit or operator : Yes 1 be 1

^ Bitwise exclusive or operator : The same thing 0, The difference is 1

~ Bitwise negation operator :0 change 1,1 change 0( I got the complement , To convert to the original code )

<< Bitwise shift left operator : Top left discard , To the right

  • Fast calculation : hold << Data on the left multiply 2 The power of the shift of : for example 3 << 2 namely :3 * 2 ^ 2 = 12

>> Bitwise shift right operator : The highest bit is 0, Left complement 0, The highest position is 1, Left complement 1

  • Fast calculation : hold >> Data on the left Divide 2 The power of the shift of : for example -24 >> 2 namely :-24 / 2 ^ 2 = -6

>>> Shift bit right to zero operator : No matter the highest position is 0 still 1 , Left complement 0

Demonstration respectively ^ and >> Two typical operators

  • 3 ^ 4
// 3 Binary system : 11 Make up the number of digits
00000000 00000000 00000000 00000011
// 4 Binary system : 100 Make up the number of digits
00000000 00000000 00000000 00000100
// Bitwise exclusive or operator : The same thing 0, The difference is 1
00000000 00000000 00000000 00000011
00000000 00000000 00000000 00000100
-----------------------------------
00000000 00000000 00000000 00000111
// What you get is the complement , Because the sign bit is 0 Is a positive number , So the original complement is the same as the inverse complement , So the result ( Original code ) It's binary 111, It's decimal 7
  • -24 >> 2
// -24 Binary system : 11000 The negative sign bit is 1, Make up the number of digits
Original code : 10000000 00000000 00000000 00011000
Inverse code : 11111111 11111111 11111111 11100111
Complement code : 11111111 11111111 11111111 11101000
// Move right 2 position The highest position is 1, Left complement 1
11111111 11111111 11111111 11101000
1111111111 11111111 11111111 111010(00)
// The result is the complement , Press 8 Separate the lines
Complement code : 11111111 11111111 11111111 11111010
Inverse code : 11111111 11111111 11111111 11111001
Original code : 10000000 00000000 00000000 00000110
// The result is binary 110, It's decimal -6

2.10 Work it out in the most efficient way 2 multiply 8 How much

Use bit operations to achieve the highest efficiency . Bit operator is to operate and operate on binary bits of operands , Operands and results are integers .

For bitwise operators << , It's moving a number to the left n position , It's like multiplying 2 Of n Power , that , A number times 8 Just move it left 3 Who can , Bit operations are cpu Directly supported , Highest efficiency .

therefore ,2 multiply 8 The most efficient way to equal a few is 2 << 3

2.11 break、continue、return The difference between ?

break、continue All belong to the keywords that jump out of the loop ,return Keywords belonging to the jump out method

  • break: Completely jump out of a loop , Execute the next statement under the loop body
  • continue: Skip this cycle , Execute next cycle
  • return: End method run , There are two uses

    • return;: For methods that have no return value ( Don't write )
    • retu
    • rn value: Used to return a specific value

3. Basic data type

3.1 Let me talk about it. Java Several basic data types in

First Java It's a strong type of language , Specific data types are defined for each type of data ( That is to constrain the range of some values , Thus, different memory spaces are allocated in memory for different types of values )

Name Size( byte \ digit ) Range
byte 1byte \ 8bit -128~127 Between
short 2bytes \ 16bit -32768~32767 Between , The maximum amount of data storage is 65536
int 4bytes \ 32bit -2^31 ~ 2^31-1 Between
long 8bytes \ 64bit -2^63 ~ 2^63-1
float 4bytes \ 32bit 3.4e-45~1.4e38, When assigning directly, you must add... After the number f or F
double 8bytes \ 64bit 4.9e-324~1.8e308, You can add d or D Or you can skip it
boolean Only true and false Two values
char 2bytes Storage Unicode code , Assign values in single quotation marks

Be careful : about boolean, Official documents do not clearly define , It depends on JVM The specific implementation of the manufacturer . Logically, it means to occupy 1 position , But in practice, we will consider the factor of efficient computer storage .

3.2 Talk about the precision processing of data type conversion

Generally speaking , We're doing calculations , It is required that the numerical types involved in the operation must be consistent , When the types are inconsistent , There are two ways to unify different data types , namely : Default auto conversion ( The transition from small to large ) and Coercive transformation .

  • Default auto conversion : From byte,short, char All three will be transferred to higher precision type by default , The order of accuracy levels is as follows ( ==> int ==> long ==> float ==> double )
doubt : Why? float(4 Bytes ) stay long(8 Bytes ) Back

A: They have different underlying storage structures

B: float The range of data represented is larger than long The scope should be large

long:2^63-1

float:3.410^38 > 210^38 > 28^38 > 22^3^38

= 2*2^144 > 2^63 -1

Default type conversion example :

// For example, low precision byte To high precision int Will be converted by default , Automatic conversion type
// It can be executed normally
public static void main(String[] args) {
byte a = 2;
int b = 3;
int c = a + b
System.out.println(c);
}
// High precision int To low precision byte There may be a loss of accuracy
// Direct error , Incompatible types : from int The switch to byte There may be losses
public static void main(String[] args) {
byte a = 3;
int b = 4;
byte c = a + b
System.out.println(c);
}
  • Cast

    • Format : Target data type Variable = ( Target data type )( Converted data )

Be careful : Don't use force conversion casually , Because it implies the problem of precision loss , Cast must be used when converting a large type to a small one .

int i = 128;
// because byte The type is 8 position , The maximum value is 127, So when int Cast to byte When it comes to type , value 128 It will lead to overflow
byte b = (byte)i;

3.2.1 What's the difference between variable addition and constant addition in type conversion

Add variables , I'll look at the type first , Finally, the assignment of the result will also consider the type problem

Constant sum , First, add , Then see if the result is in the range of the assigned data type , If not , It's a mistake

3.2.2 Java Behind it is how to cast byte Type overflow error problem

public static void main(String[] args) {
// byte The range is : -128 To 127, So wrong reporting
byte a = 130;
// Use cast
byte b = (byte)130;
System.out.println(b);
}

We want to know what the result is , You should know how to calculate , And we also know that the operation of data in computer is carried out by complement code , Get the complement , The first step is to calculate the binary of the data

// Find out 130 Binary system 10000010
// 130 It's an integer So fill in 4 Bytes ( A byte 8 position )
0000000 00000000 00000000 10000010
// Do intercept operation , Cut into byte type (1 Bytes ,8 position )
10000010
// The above result is a complement , Find the source code
Complement code : 10000010
Inverse code : 10000001
Original code : 11111110
// 11111110 Convert to decimal to -126

3.3 Java What is the packaging type corresponding to the basic type in , What is automatic packing and unpacking ?

Java There is 8 Basic data types , Respectively :byte、short、int、long、float、double、char、boolean.

The corresponding packaging classes are :Byte、Short、Integer、Long、Float、Double、Character、Boolean

The advantage of encapsulating a basic data type as an object is that more functional methods can be defined in the object to manipulate the data , such as String and int Conversion of types . At the same time, it simplifies the transformation steps of basic data types and corresponding objects .

  • Automatic boxing : Wrap basic types with their corresponding reference types
  • Automatic dismantling : Convert wrapper type to base data type

And when we want to use some methods of the wrapper class , You can pass in values through the construction method of the basic type wrapper class , however JDK5 The new features greatly simplify some troublesome steps for us .

// Define a Packaging type Integer Receive a basic type int Integers 1, This is an automatic boxing .
Integer a = 1;
// If there is no automatic packing , You need to use constructors
Integer a = new Integer(1)
// Keep using int type b Receive one The type of packaging on it Integer a, This is an automatic unpacking
int b = a;
// If there is no automatic unpacking , You need to use the method
int b = a.intValue()

3.4 Constant pools of several types of wrapper classes ( buffer ) problem

stay JDK 5 in the future , Several wrapper class objects refer to real objects by using the same object in their internal implementation Now caching and reuse . for example :Integer Type for -128-127 The number between is in the buffer , So for values in this range, use the double equal sign (==) The comparison is consistent , Because the corresponding memory address is the same . But for numbers that are not in this range, they are in the heap new Coming out , So the address space is different , It's not equal .

  • Byte、Short、Integer、Long Cache range :[-128,127]
  • Character Cache range :[0,127]
  • Boolean Go straight back to True Or False

notes : Floating point type packaging class Float and Double Constant pool technology is not implemented

Boolean Source excerpt :

// Define from the beginning TRUE FALSE Two constants
public static final Boolean TRUE = new Boolean(true);
public static final Boolean FALSE = new Boolean(false);
// This constructor is rarely used , Static factory is recommended when not necessary
public Boolean(boolean value) {
this.value = value;
}
// valueOf It's a better choice , It can produce better time and space performance
public static Boolean valueOf(boolean b) {
return (b ? TRUE : FALSE);
}

Character Source excerpt :

// This method usually takes precedence over constructors , The reason is also to produce better time and space performance
public static Character valueOf(char c) {
if (c <= 127) { // must cache
return CharacterCache.cache[(int)c];
}
return new Character(c);
}
// The specific logic is here
private static class CharacterCache {
private CharacterCache(){}
static final Character cache[] = new Character[127 + 1];
static {
for (int i = 0; i < cache.length; i++)
cache[i] = new Character((char)i);
}
}

Integer Source excerpt :

// The method always caches values in -128 To 127 Between , And possibly cache other values out of that range
public static Integer valueOf(int i) {
if (i >= IntegerCache.low && i <= IntegerCache.high)
return IntegerCache.cache[i + (-IntegerCache.low)];
return new Integer(i);
}
// IntegerCache The concrete logic can be studied by oneself 

4. Method

4.1 Java Method parameters are passed as values or references in

Java The method parameter passing method in is Pass by value .

  • If the parameter is Basic types , It's the literal quantity of the basic type Copy of value . The effect of the change of formal parameters on the actual parameters No impact
  • If the parameter is Reference type , What is passed is that the object referenced by this parameter is in the heap A copy of the address value . Changes in formal parameters direct influence The actual parameter

Let's make a simple analysis of the above conclusions :

Example 1:

public static void main(String[] args) {
// Basic types
int a = 100;
int b = 200;
System.out.println("main call modify front : " + "a: " + a + ", b: " + b);
modify(a, b);
System.out.println("main call modify after : " + "a: " + a + ", b: " + b);
}
/**
* Parameters are basic types
* @param a
* @param b
*/
public static void modify(int a, int b) {
System.out.println("modify Parameters received : " + "a: " + a + ", b: " + b);
a = 300;
b = 400;
System.out.println("modify After modifying the parameters : " + "a: " + a + ", b: " + b);
}

Running results :

main call modify front : a: 100, b: 200
modify Parameters received : a: 100, b: 200
modify After modifying the parameters : a: 300, b: 400
main call modify after : a: 100, b: 200

Example 2:

public static void main(String[] args) {
// Reference type
int[] arr = {1, 2, 3, 4, 5};
System.out.println("main call modify front : " + "arr[0]: " + arr[0]);
modify(arr);
System.out.println("main call modify after : " + "arr[0]: " + arr[0]);
}
/**
* Parameter is reference type
* @param arr
*/
public static void modify(int[] arr) {
System.out.println("modify Parameters received ( With arr[0] give an example ): " + "arr[0]: " + arr[0]);
arr[0] = 100;
System.out.println("modify After modifying the parameters ( With arr[0] give an example ): " + "arr[0]: " + arr[0]);
}

Running results :

main call modify front : arr[0]: 1
modify Parameters received ( With arr[0] give an example ): arr[0]: 1
modify After modifying the parameters ( With arr[0] give an example ): arr[0]: 100
main call modify after : arr[0]: 100

The result of the above code , namely : Take the base type as the method parameter , Modification of formal parameters in method , It doesn't affect the actual parameters . Take the reference type as the method parameter , Modification of formal parameters in method , Will directly affect the actual parameters . Draw a picture and analyze it briefly :

For basic types ,a and b , stay modify(int, int) Method does not affect the original value , This is because modify Method a and b It's from the original a and b A copy of it . No matter what a and b Value , Will not affect the original value .

For reference types ,arr After initializing the array , Point to a specific address , And pass it as a method parameter ,modify Methods arr It also points to the same address , So the modification in the method , Will be directly reflected in the corresponding object .

4.2 Let's talk about the difference between method overloading and rewriting

Method overloading : In a class , If a method with the same name has a different parameter list ( Parameter type 、 The number is even different in order ) It's called overloading

  • The rules : In the same class , Method name must be the same , Different parameter types 、 The number is different. 、 Different order , Method return values and access modifiers can be different .
  • form : Method name , Return value , Access modifier , Same method , According to different data lists , Make different logical processes .

Method rewriting : Is a subclass to the parent class to allow access to the method of the implementation process to be rewritten

  • The rules

    • Method name 、 parameter list 、 If the return types are the same , Modify or rewrite the legal entity .
    • The access modifier limit must be greater than the access modifier of the overridden method (public > protected > default > private).
    • The overriding method must not throw a new check exception or a more general check exception than the overridden method declaration
  • form : Overriding is the same method that a subclass inherits from its parent , Enter the same data , You're going to override the parent method , So that the method can make different responses

4.2.1 How to understand method overloading and rewriting is the way to realize polymorphism

Method overloading and rewriting are ways to implement polymorphism , The difference is that overloading implements polymorphism at compile time , Rewriting implements polymorphism at runtime

sex . Polymorphism here can be understood as a method of call , Or different function entry parameters , And the resulting methods and behaviors are different .

Two different periods of polymorphism :

  • Compile time polymorphism : It is also called static polymorphism , Polymorphism at compile time is achieved by overloading , According to the number of parameters , Type and order determine ( Must be in the same class )

    • Before the method call , The compiler has determined which method to call , This is called “ Early binding ” or “ Static binding ” ;
  • Run time polymorphism : Runtime polymorphism is achieved by rewriting methods , Treated as the same method during compilation , But during the run time, different methods are called according to different objects

    • Only when the method is called , The interpreter runner will determine the specific method to be called , This is called “ Late binding ” or “ Dynamic binding ” .
    • That's what we're talking about , Compile to the left , Run to the right ( In the object-oriented chapter, we will discuss )

4.2.1 Why can't functions distinguish overloads by return type ?

Java Allow any method to be overloaded , It's not just the constructor method . Therefore, the method name and parameter type should be indicated completely . This is called the signature of the method (signature). for example String Like 4 One is called indexOf Public method of . Their signature is :

indexOf(int)
indexOf(int, int)
indexOf(String)
indexOf(String, int)

The return value type is not part of the method signature . in other words , There can't be two names that are the same 、 Methods that return different types of values with the same parameter type .

At the same time, the return value of the function is only one after the function is run “ state ”, It is the key to keep the caller of the method communicating with the callee . It can't be used as a method “ identification ”.

版权声明
本文为[BWH_ Steven]所创,转载请带上原文链接,感谢
https://javamana.com/2021/01/20210122134849882u.html

  1. 【计算机网络 12(1),尚学堂马士兵Java视频教程
  2. 【程序猿历程,史上最全的Java面试题集锦在这里
  3. 【程序猿历程(1),Javaweb视频教程百度云
  4. Notes on MySQL 45 lectures (1-7)
  5. [computer network 12 (1), Shang Xuetang Ma soldier java video tutorial
  6. The most complete collection of Java interview questions in history is here
  7. [process of program ape (1), JavaWeb video tutorial, baidu cloud
  8. Notes on MySQL 45 lectures (1-7)
  9. 精进 Spring Boot 03:Spring Boot 的配置文件和配置管理,以及用三种方式读取配置文件
  10. Refined spring boot 03: spring boot configuration files and configuration management, and reading configuration files in three ways
  11. 精进 Spring Boot 03:Spring Boot 的配置文件和配置管理,以及用三种方式读取配置文件
  12. Refined spring boot 03: spring boot configuration files and configuration management, and reading configuration files in three ways
  13. 【递归,Java传智播客笔记
  14. [recursion, Java intelligence podcast notes
  15. [adhere to painting for 386 days] the beginning of spring of 24 solar terms
  16. K8S系列第八篇(Service、EndPoints以及高可用kubeadm部署)
  17. K8s Series Part 8 (service, endpoints and high availability kubeadm deployment)
  18. 【重识 HTML (3),350道Java面试真题分享
  19. 【重识 HTML (2),Java并发编程必会的多线程你竟然还不会
  20. 【重识 HTML (1),二本Java小菜鸟4面字节跳动被秒成渣渣
  21. [re recognize HTML (3) and share 350 real Java interview questions
  22. [re recognize HTML (2). Multithreading is a must for Java Concurrent Programming. How dare you not
  23. [re recognize HTML (1), two Java rookies' 4-sided bytes beat and become slag in seconds
  24. 造轮子系列之RPC 1:如何从零开始开发RPC框架
  25. RPC 1: how to develop RPC framework from scratch
  26. 造轮子系列之RPC 1:如何从零开始开发RPC框架
  27. RPC 1: how to develop RPC framework from scratch
  28. 一次性捋清楚吧,对乱糟糟的,Spring事务扩展机制
  29. 一文彻底弄懂如何选择抽象类还是接口,连续四年百度Java岗必问面试题
  30. Redis常用命令
  31. 一双拖鞋引发的血案,狂神说Java系列笔记
  32. 一、mysql基础安装
  33. 一位程序员的独白:尽管我一生坎坷,Java框架面试基础
  34. Clear it all at once. For the messy, spring transaction extension mechanism
  35. A thorough understanding of how to choose abstract classes or interfaces, baidu Java post must ask interview questions for four consecutive years
  36. Redis common commands
  37. A pair of slippers triggered the murder, crazy God said java series notes
  38. 1、 MySQL basic installation
  39. Monologue of a programmer: despite my ups and downs in my life, Java framework is the foundation of interview
  40. 【大厂面试】三面三问Spring循环依赖,请一定要把这篇看完(建议收藏)
  41. 一线互联网企业中,springboot入门项目
  42. 一篇文带你入门SSM框架Spring开发,帮你快速拿Offer
  43. 【面试资料】Java全集、微服务、大数据、数据结构与算法、机器学习知识最全总结,283页pdf
  44. 【leetcode刷题】24.数组中重复的数字——Java版
  45. 【leetcode刷题】23.对称二叉树——Java版
  46. 【leetcode刷题】22.二叉树的中序遍历——Java版
  47. 【leetcode刷题】21.三数之和——Java版
  48. 【leetcode刷题】20.最长回文子串——Java版
  49. 【leetcode刷题】19.回文链表——Java版
  50. 【leetcode刷题】18.反转链表——Java版
  51. 【leetcode刷题】17.相交链表——Java&python版
  52. 【leetcode刷题】16.环形链表——Java版
  53. 【leetcode刷题】15.汉明距离——Java版
  54. 【leetcode刷题】14.找到所有数组中消失的数字——Java版
  55. 【leetcode刷题】13.比特位计数——Java版
  56. oracle控制用户权限命令
  57. 三年Java开发,继阿里,鲁班二期Java架构师
  58. Oracle必须要启动的服务
  59. 万字长文!深入剖析HashMap,Java基础笔试题大全带答案
  60. 一问Kafka就心慌?我却凭着这份,图灵学院vip课程百度云