Preparatory knowledge
What is java?
java is a high-level programming language launched by Sun company in 1995. It is a computer language. People can use the programming language to give instructions to the computer and let the computer complete the functions that people need.
What can java do?
java can write desktop applications, Web applications, distributed systems and embedded system applications.
What is binary?
Most people use the decimal system in their life, while all computers use binary numbers for representation. It only contains two numbers: 0 and 1. Every two into one, and each 0 or 1 is called a bit.
What are bytes?
Byte is the smallest storage unit in the computer. Any data stored in the computer is stored in the form of byte.
JDK,JRE,JVM
JDK is a java program development kit, including tools used by JRE and developers. It is used to compile and debug Java programs; JRE is the running environment of Java programs, including the JVM and the core class library required by the runtime; JVM is a Java virtual machine, which is responsible for interpreting bytecode into specific machine code.
Java program running process
To run a Java program, first write a Java source file, then javac compiles the source file into a bytecode file recognized by the JVM, and finally load and run the generated class bytecode file.
Basic grammar
Keywords, identifiers
Keywords refer to the words defined by java in the program, which have special meanings. java keywords are expressed in lowercase letters. Identifier refers to the content defined by ourselves in the program, such as class name, method name, variable name, etc. The identifier can contain 26 upper and lower case letters, 0-9 numbers, $and; Identifier cannot start with a number; Cannot be a keyword.
Naming specification: project name and package name are all lowercase; Constant names are capitalized and used between words_ connect; Big hump is used for file name and class name; Small hump is used for method name and variable name.
Constant, variable
Constant refers to the fixed data in java program. Constant includes integer, floating point number, Boolean, character, string and empty constant. Variables refer to data that can be changed in java programs.
Define three elements of variables: data type, variable name and data value.
Data type and type conversion
Data types in java are divided into basic data types and reference data types. The basic data types are divided into four categories and eight types, namely byte, short, int, long, float, double, char and boolean; The reference data types are class, array and interface. When the data types are different, data type conversion will occur. Automatic type conversion occurs when the data range is assigned from small to large; When the data range is from large to small, forced type conversion is required, that is, add (data type) before the data to be forced. Strong rotation may cause accuracy loss and data overflow, which should be used with caution.
Note: byte\short\char data type will be promoted to Int type before calculation.
operator
Arithmetic operator
In the process of arithmetic operation, once there are different types of data for calculation, the data type of the result will be the data type with a wide range of data types. In the self increment and self subtraction operator, if it is the first self increment, it is added first and then used, and the latter self increment is used first and then added. The same is true for self subtraction.
addition | subtraction | multiplication | division | Seeking module | Self increasing | Self subtraction |
---|---|---|---|---|---|---|
+ | - | * | / | % | ++ | – |
Assignment Operators
Only variables can use assignment operators, and constants cannot be assigned.
be equal to | Add etc | Subtraction | Wait by | Divide and so on | Module, etc |
---|---|---|---|---|---|
= | += | -= | *= | /= | %= |
Comparison operator
The result of the comparison operator must be a boolean value. If it is true, it will be false.
wait | greater than | less than | Big class | Wait | Unequal |
---|---|---|---|---|---|
== | > | < | >= | <= | != |
Logical operator
&&All is true|| All false is false;! It's negative, either true or false. Logical operators can only be used with boolean values.
And | or | wrong |
---|---|---|
&& | || | ! |
Ternary operator
Operators that require three data to operate are called ternary operators. The ternary operator must ensure that all expressions meet the requirements of the data type on the left, and the result must be used.
public class Demo { public static void main(String[] args) { // 10 is greater than 9? If yes, assign 1 to num, otherwise assign 0 to num int num = 10 > 9 ? 1 : 0; // Print out the value of num System.out.println(num); // 1 } }
Process control
Sequential structure
Sequential structure is the simplest program structure, and its execution order is from top to bottom.
public class Demo { public static void main(String[] args) { System.out.println("one"); // one System.out.println("two"); // two System.out.println("three"); // three } }
Select structure
The selection structure can be divided into single if conditional statement, if ···· else conditional statement, if ··· else if multi branch statement and switch multi branch statement.
public class Demo { public static void main(String[] args) { switch (2) { case 0 : if (1 < 2) { System.out.println("one"); } break; case 1 : if (1 > 2) { System.out.println("two"); } else { System.out.println("three"); } break; default: if (1 > 2) { System.out.println("four"); } else if (1 > 3) { System.out.println("five"); } else { System.out.println("six"); } break; } } }
Note: the value after multiple case s in switch cannot be repeated.
Cyclic structure
The loop structure can be divided into for loop, while loop and do ··· while loop. If the condition is never met, the for loop and the while loop will not be executed once, while the do ··· while loop will be executed at least once.
public class Demo { public static void main(String[] args) { do { for (int i = 1; i <= 9; i++) { int j = 1; while (j <= i) { System.out.printf("%d X %d = %-5d", i, j, i * j); j++; } System.out.println(); } } while (false); } }
break,continue
break is used in switch to terminate switch, and in loop to terminate loop; continue is used in the loop to skip this loop and start the next loop immediately.
public class Demo { public static void main(String[] args) { for (int i = 1; i < 9; i++) { if (i == 3) { continue; } if (i == 6) { break; } System.out.println("i = " + i); } } }
method
The method is to extract the code to form a separate function, which can be called when we need to use this function, which not only solves the reusability of the code, but also solves the phenomenon of code redundancy. The order of method definitions does not matter; After the method is defined, it needs to be called before execution; The three call formats of method are individual call, print call and assignment call.
public class Demo { public static void main(String[] args) { method("java"); // JAVA } public static void method(String s) { // Print the string s in uppercase format System.out.println(s.toUpperCase()); } }
Define three elements of a method: return value type, method name, and parameter list.
array
Array is a kind of container, which can store multiple elements with unified data types at the same time. The length of the array cannot be changed during the running of the program. If you are not sure about the specific contents of the array, use dynamic initialization, otherwise use static initialization. When dynamic initialization is used, its array elements will automatically have default values; Static initialization actually has a default value process, but the system automatically replaces the default value with the specific value in braces. Array name Length gets the length of the array.
All reference types can be assigned a null value, but it means there is nothing in them. The array must be initialized with new before its elements can be used. If only a null is assigned and it is used without new creation, a null pointer exception will occur.
import java.util.Arrays; public class Demo { public static void main(String[] args) { int arr1[] = new int[3]; int arr2[] = new int[] {1, 2, 3}; int arr3[] = {1, 2, 3}; System.out.println(Arrays.toString(arr1)); // [0, 0, 0] System.out.println(Arrays.toString(arr2)); // [1, 2, 3] System.out.println(Arrays.toString(arr3)); // [1, 2, 3] } }
Note: any data type can be used as the parameter type or return value type of the method. Array is the parameter of the method. What is passed in is the address value of the array; In fact, the value returned by the array method is also the value returned by the array method.
object-oriented
Object oriented thought
java is a pure object-oriented programming language, and object-oriented is a programming idea. The object here generally refers to all things in reality, and each thing has its own attributes and behavior. The object-oriented idea refers to the real things in programming, and abstracts the attribute characteristics and behavior characteristics of things to describe the design idea of computer events. Different from the process oriented idea, it emphasizes that the function is realized by calling the behavior of the object, rather than operating and realizing it step by step.
Object oriented thinking is an idea that is more in line with our thinking habits. It can simplify complex things and turn us from executor to commander. The three characteristics of object-oriented are encapsulation, inheritance and polymorphism.
Class, object
Class is a set of related attributes and behaviors, which can be regarded as the template of a class of things. It is described by the attribute characteristics and behavior characteristics of things. Attribute is the state information of the thing, that is, member variables; Behavior is what the thing can do, that is, member method. Member methods are directly defined in the class. Outside the method, if the member variable is not assigned, it will have its default value.
Object is the concrete embodiment of a class of things. Object is an instance of a class and has the attributes and behavior of such things. Class is the description of a class of things, which is abstract; An object is an instance of a class of things and is concrete. Class is the template of object, and object is the entity of class.
Note: local variables are located in the stack. They are born with the method entering the stack and disappear with the method leaving the stack; The member variable is located in the heap, which is born when the object is created and disappears when the object is garbage collected.
Construction method
Construction method is a method specially used to create objects. When we create objects through the keyword new, we are actually calling the construction method.
class Person { public String name; public Person() { System.out.println("Parameterless construction method execution!"); } public Person(String name) { System.out.println("Parameter construction method execution! Name is" + name); } } public class Demo { public static void main(String[] args) { Person person1 = new Person(); // Parameterless construction method execution! Person person2 = new Person("Iron head baby"); // Parameter construction method execution! Her name is tietouwa } }
Note: the name of the constructor must be exactly the same as the class name of the class, and the constructor does not need to return a value.
Anonymous object
Anonymous objects are objects that have only the right of the equal sign, without the left name and assignment operator. Anonymous objects can be used if it is determined that an object needs to be used only once.
import java.util.Random; public class Demo { public static void main(String[] args) { // Get and print random numbers between 1 and 10 System.out.println(new Random().nextInt(10) + 1); } }
Overload,Override
Overload. In the definition of methods, the names of methods are the same and the parameter lists are different.
Override. In the inheritance relationship, the name of the method is the same, and the parameter list is the same.
When overriding a method, you must ensure that the name of the method and the parameter list between the parent and child classes are the same. The annotation @ Override is used to detect whether it is a valid method Override; The return value of the subclass method must be less than or equal to the return value range of the parent method; The permission modifier of the subclass method must be greater than or equal to the permission modifier of the parent method.
Design principle: for the classes that have been put into use, try not to modify them. It is recommended to define a new class to reuse the common contents and add and change new contents.
class SuperClass { public int methodInt(int i) { return i; } public double methodInt(double d) { return d; } } class SubClass extends SuperClass { @Override public int methodInt(int i) { return 2 * i; } } public class Demo { public static void main(String[] args) { System.out.println(new SubClass().methodInt(100)); // 200 System.out.println(new SubClass().methodInt(1.1)); // 1.1 } }
static
Once a member in a class is modified with static static, the member will no longer belong to the object itself, but to the class itself; It can be used through the class name without creating an object. It is generally recommended to use the class name to call static methods. Static can not directly access non static, because in the program is the first static content, and then some non static content, "ancestors do not know future generations, but future generations know their ancestors!" Static methods cannot use this, because this represents the current object. Whoever invokes the method is the current object, while static members belong to classes and do not belong to an object.
The execution priority of static code block is higher than that of construction method. It will be executed once during class initialization and will be destroyed after execution. It can only initialize class variables, that is, data members decorated with static.
class Person { static { System.out.println("Static code block execution!"); } public static int age = 100; public static void method() { System.out.println("Man is a superior animal !"); } } public class Demo { public static void main(String[] args) { System.out.println(Person.age); Person.method(); } } /*---------------------------------------- Static code block execution! 100 Man is a superior animal ! ----------------------------------------*/
this,super
This represents the current object reference of the class. It is an address value. The method represented by this object is the method that is called. super is a reference to the parent class, which is used to access the content of the parent class, while this is used to access the content of this class.
There are three uses of this:
- In the member method of this class, access the member variables of this class.
- In the member method of this class, access another member method of this class.
- In the constructor of this class, access another constructor of this class.
There are three uses of super:
- In the member method of the subclass, access the member variable of the parent class.
- In the member method of the subclass, access the member method of the parent class.
- In the constructor of the subclass, access the constructor of the parent class. There is actually a default implicit super() call in the construction method of a subclass, so the construction method of the parent class must be called first, and then the construction method of the subclass must be executed; Subclass construction can also call parent class overload construction through super keyword; The subclass must call the constructor of the parent class. If it is not written, it will be given a super(). If it is written, it will be called by itself. There can only be one super, and it must be the first statement.
class SuperClass { int num = 10; public void methodA() { System.out.println(num); } } class SubClass extends SuperClass { int num = 20; public SubClass() { this(40); } public SubClass(int num) { super(); System.out.println(this.num); } public void methodA() { int num = 30; System.out.println(num); System.out.println(this.num); System.out.println(super.num); } public void methodB() { methodA(); super.methodA(); } } public class Demo { public static void main(String[] args) { new SubClass().methodB(); } } /*---------------------------------------- 20 30 20 10 10 ----------------------------------------*/
final
The final keyword can be used to modify references, methods and classes. Once the final keyword is used for modification, the description cannot be changed.
- After final modifies the basic data type, the value of the reference is constant and cannot be modified.
- After final modifies the reference data type, the address value of the reference cannot be modified.
- After final modifies the member variable of the class, it must be assigned immediately, otherwise it will compile and report an error.
- After final is used to modify a method, the method will become the final method and can be inherited by subclasses, but this method cannot be overridden.
- Final is used to modify a class, which will become the final class and cannot be inherited, that is, the "class without children".
final class SuperClass { public SuperClass() { System.out.println("Constructor execution in the final class"); } public static final int I = 11; public final String STR = "Unchangeable String"; final void method() { System.out.println("Unchangeable method"); } } public class Demo { public static void main(String[] args) { System.out.println(SuperClass.I); System.out.println(new SuperClass().STR); new SuperClass().method(); } } /*---------------------------------------- 11 Constructor execution in the final class String that cannot be changed Constructor execution in the final class method that cannot be changed ----------------------------------------*/
encapsulation
Encapsulation is to hide some detailed information from the outside world. Method and keyword private are encapsulation. Once the member variable is decorated with private, it can only be accessed directly in this class; Indirect access to members modified by private is to define a pair of Getter/Setter methods. For Getter, there can be no parameters, and the return value type corresponds to the member variable; Setter cannot have a return value. The parameter type corresponds to the member variable.
Note: for boolean values, the Getter method must be written in the form of isXxx, and the setXxx rule remains unchanged.
class Person { private String name; public Person() { } public Person(String name) { this.name = name; } public String getName() { return name; } public void setName(String name) { this.name = name; } } public class Demo { public static void main(String[] args) { Person person = new Person("Iron head baby"); person.setName("hothead"); String name = person.getName(); System.out.println(name); // hothead } }
inherit
Inheritance is the premise of polymorphism. Without inheritance, there will be no polymorphism; The main problem of inheritance is commonality extraction. java is single inheritance. There can only be one direct parent class of a class, but a parent class can have multiple subclasses; java can inherit at multiple levels, that is, the parent class can also have its own parent class.
Characteristics of inheritance relationship:
- In the inheritance relationship, in addition to inheriting all inheritable contents in the parent class, the child class can also have its own proprietary contents.
- "A subclass is a parent", that is, a subclass can be treated as a parent.
- Whether accessing member methods or member variables, if there is no, you will always look up for the parent class and never look down for the child class.
class SuperClass { public int num = 10; public SuperClass() { System.out.println("Parent class construction method execution!"); } public void methodA() { System.out.println("Parent method methodA Execution, num by" + num); } } class SubClass extends SuperClass { public int num = 20; public SubClass() { System.out.println("Subclass construction method execution!"); } public void methodB() { int num = 30; System.out.println("Subclass method methodB Execution, num by" + num); } } class Grandson extends SubClass { public void methodC() { System.out.println("Subclass method methodC Execution, num by" + num); } } public class Demo { public static void main(String[] args) { new SuperClass().methodA(); new SubClass().methodB(); new Grandson().methodC(); } } /*---------------------------------------- Parent class construction method execution! The parent class method methodA is executed, and num is 10 Parent class construction method execution! Subclass construction method execution! The subclass method methodB is executed, and num is 30 Parent class construction method execution! Subclass construction method execution! The descendant method is executed by methodC, and num is 20 ----------------------------------------*/
Abstract class, abstract method
If the method in the parent class is not sure how to implement the {} method body, it should be an abstract method. The abstract method is to add the abstract keyword after the permission modifier, then remove the braces and end directly with a semicolon; The class of the abstract method must be an abstract class. Just add the abstract keyword before the class. An abstract class does not necessarily contain abstract methods, as long as the class where the abstract methods are located is an abstract class. In this way, abstract classes without abstract methods cannot directly create objects, which are useful in some special scenarios.
The use of abstract classes. Abstract classes cannot directly create new abstract class objects; You must override all the abstract methods in the parent class and override all the abstract methods in the parent class. For classes and methods, abstract and final cannot be used at the same time because of contradictions.
abstract class Person { public abstract void work(); } class Programmer extends Person { @Override public void work() { System.out.println("Programmers type code every day !"); } } public class Demo { public static void main(String[] args) { new Programmer().work(); // Programmers type code every day ! } }
Interface
In our daily life, the interface is a public standard. As long as it meets the standard, it can be used by everyone. In java program, the interface is a reference data type, and the most important content is the abstract method. The format of defining the interface is actually to replace the class keyword class with the interface interface. After replacing it with the interface, it is still the interface java source file compiled into Class bytecode file.
- In any version of JDK, interfaces can define abstract methods.
For the abstract method in the interface, the modifier must be two fixed Keywords: public abstract, which can be selectively omitted; The three elements of the method can also be defined at will.
The use of interfaces, which cannot be used directly, must have an implementation class to implement the interface; The implementation class of the interface must override all abstract methods in the rewriting (Implementation) interface.
- In JDK7, interfaces can contain constants.
In fact, the "member variable" can also be defined in the interface, but it must be decorated with the three keywords public static final. From the effect, this is actually a constant in the interface. Constants in the interface must be assigned values, and the public static final keyword can be omitted.
- In JDK8, the interface can contain default methods and static methods;
The default method in the interface can solve the problem of interface upgrade; Class objects can be called directly through the interface; Can be overridden by interface implementation classes.
The static method in the interface cannot call the static method in the interface through the object of the interface implementation class, but its static method can be called directly through the interface name.
- In JDK9, interfaces can contain private methods.
Ordinary private methods can solve the problem of repeated code between multiple default methods, while static private methods can solve the problem of repeated code between multiple static methods. Private methods can only be called by the interface itself, and cannot be used by implementation classes or others.
interface Test { public static final String STR = "Java"; public abstract void methodA(); public default void methodB() { System.out.println("The default method in the interface is executed!"); methodD(); } public static void methodC() { System.out.println("The static method in the interface is executed!"); } private void methodD() { System.out.println("The ordinary private method in the interface is executed!"); methodE(); } private static void methodE() { System.out.println("The static private method in the interface is executed!"); } } class TestImpl implements Test { @Override public void methodA() { System.out.println("The implementation class overrides the implementation of the abstract method in the interface!"); } @Override public void methodB() { System.out.println("The implementation class overrides the default method execution in the interface!"); } } public class Demo { public static void main(String[] args) { Test.methodC(); // The static method in the interface is executed! } }
matters needing attention:
- Interfaces have no static code blocks or constructors.
- The direct parent class of a class is unique, but a class can implement multiple interfaces at the same time.
- If there are duplicate abstract methods in multiple interfaces implemented by the implementation class, it only needs to be overwritten once.
- If the implementation class does not cover all the abstract methods in the rewriting interface, the implementation class itself must be an abstract class.
- If there are duplicate default methods in multiple interfaces implemented by the implementation class, the implementation class must override the conflicting default methods.
- If the method of the direct parent of a class conflicts with the default method in the interface, the method of the parent class takes precedence.
- There is single inheritance between classes, and there is only one direct parent class.
- There are multiple implementations between classes and interfaces. A class can implement multiple interfaces.
- There are multiple inheritance between interfaces.
- If the abstract method in multiple parent interfaces is repeated, it doesn't matter. If the default method in multiple parent interfaces is repeated, the child interface must overwrite the default method with the default keyword.
polymorphic
Inheritance or interface implementation is the premise of polymorphism. The embodiment of polymorphism in the code is actually a sentence: the parent class reference points to the child class object. Access member variables, compile and run on the left; Access member methods, compile to the left and run to the right.
The upward transformation of objects is actually a polymorphic writing method, which treats and uses subclass objects as parent classes. Upward transformation must be safe. It changes from a small scope to a large scope, but there is also a disadvantage. Once the object is transformed upward into a parent class, it will not be able to call the original unique content of the child class. The solution is to use the downward transformation of the object, that is, the restore action, that is, to restore the parent object to the original child object. The downward transformation must ensure that the object is the object when it is originally created before the downward transformation can succeed. Otherwise, the ClassCastException class transformation exception will be thrown.
How can I know what subclass the object referenced by a parent class is originally? Use (object name instanceof class name) to get a boolean value result, that is to judge whether the previous object can be used as an instance of a large type later.
class Animal { public void eat() { System.out.println("Animals eat!"); } } class Dog extends Animal { public void sleep() { System.out.println("Dog sleep!"); } } public class Demo { public static void main(String[] args) { Dog dog = new Dog(); Animal animal = dog; animal.eat(); Dog gou = (Dog) animal; gou.sleep(); } }
Permission modifier
public | protected | (default) | private | |
---|---|---|---|---|
In the same class | √ | √ | √ | √ |
In the same package | √ | √ | √ | |
Different package parent-child classes | √ | √ | ||
Non subclasses of different packages | √ |
Inner class
An inner class is a class that contains another thing.
- Member inner class
The inner class of a member is the class side by side with the member method. When used, the inner and outer classes can be accessed at will, while the outer classes need the inner class object. The methods of using inner classes of members can be divided into direct methods and indirect methods. The direct method is new external class name () New internal class name (); The indirect way is to use the inner class in the method of the outer class, and then the main method calls the method of the outer class.
class Test { public int num = 10; public void method() { int num = 20; System.out.println(num); // 20 System.out.println(new TestInternal().num); // 30 } class TestInternal { int num = 30; public void method() { int num = 40; System.out.println(num); // 40 System.out.println(this.num); // 30 System.out.println(Test.this.num); // 10 } } } public class Demo { public static void main(String[] args) { new Test().method(); new Test().new TestInternal().method(); } }
- Local inner class
If a class is defined inside a method, it is a local inner class, including anonymous inner classes. Only the current method can be used. It cannot be used outside this method. If the local inner class wants to access the local variable of the method, the local variable must be valid final.
Starting from JDK8, as long as the local variable fact remains unchanged, the final keyword can be omitted. Because the new object is in the heap memory, the local variable follows the method. In the stack memory, the method will be out of the stack immediately after running, and the local face will disappear immediately. However, the new object will continue to exist in the heap until it is garbage collected.
If the implementation class of the interface or the subclass of the parent class only needs to be used once, in this case, you can omit the definition of the class and use the anonymous inner class instead. When defining an anonymous inner class (new interface name () {·}), new represents the action of creating an object. The interface name is the interface that the anonymous inner class needs to implement, and {·} is the content of the anonymous inner class.
When defining a class, external classes can use public/(default); Class permission modifiers within members can be used; Local internal classes cannot write anything.
Anonymous internal classes can only be used once when creating objects. If you want to create objects multiple times and the content of the class is the same, you need to define the implementation class separately; Anonymous objects can only call methods once. If you want the same object to call methods multiple times, you must give the object a name; Anonymous inner class omits the implementation class / subclass name, while anonymous object omits the object name. Anonymous inner class and anonymous object are not the same thing!
public class Demo { public static void main(String[] args) { class TestInternal { final int NUM = 10; public void method() { System.out.println(this.NUM); } } new TestInternal().method(); // 10 new TestInternal() { final int NUM = 20; public void method() { System.out.println(this.NUM); } }.method(); // 20 new Thread(new Runnable() { @Override public void run() { System.out.println(Thread.currentThread().getName() + "Thread execution!"); } }).start(); // Thread-0 thread is executing! } }