Features of Java Language
1. Object Oriented
Object-Oriented (OOP) is the foundation of the Java language and an important feature of the Java language. Object-oriented concept: everything in life can be called an object, and things that can be seen everywhere in life are an object. We can extract and extract the state characteristics (attributes) and behavior characteristics (methods) of these things, and represented in a fixed form.
2. Simple and easy to use
The Java language is evolved from C and C++. It omits all the incomprehensible and confusing features (such as pointers) in the C language, and becomes more rigorous, concise, and easy to use.
3. Robustness
Java's security check mechanism kills many program errors in the blue. In addition, the Java language also has many features to ensure program stability and robustness (strong type mechanism, exception handling, automatic garbage collection, etc.), which effectively reduces errors and makes Java applications more robust.
4. Security
Java is usually used in the network environment, for this reason, Java provides a security mechanism to prevent malicious code attacks, which can improve the security of the system.
5. Platform independence
The Java platform independence is realized by the Java virtual machine, and Java software can run normally in any computer environment without being constrained by computer hardware and operating system.
6. Support multi-threading
There is no built-in multi-threading mechanism in the C++ language, so the multi-threading function of the operating system must be invoked for multi-threaded programming, while the Java language provides multi-threading support. The multi-threading mechanism enables the application program to execute multiple tasks in parallel at the same time, which enables the program to have better interactivity and real-time performance.
7. Distributed (support network programming)
The Java language has powerful and easy-to-use network capabilities and is very suitable for developing distributed computing programs. Java provides a network application programming interface (java.net), which enables us to remotely access objects through URL, Socket, etc.
8. Compilation and interpretation coexist
Java is a language where compilation and interpretation coexist
Java Syntax Basics
Identifier: A valid sequence of characters used to identify class names, object names, variable names, method names, type names, array names, and file names.
Legal identifiers:
- It consists of letters, numbers, underscore "_", dollar sign "$" or "¥", and the first character cannot be a number.
- Java keywords and reserved words cannot be used as identifiers.
- Identifiers are case sensitive.
Keywords: reserved words that have been given a specific meaning in the Java languageconst、goto
: , not used in Java versions, but may be used as keywords in future versions
Variable: A quantity that can be changed while the program is running. To use a variable in a program, you must first create it and give it a name, and specify the type of information it can store. This is called "variable declaration", also called the creation of a container.
Use of variables:
- Variable declaration: data type variable name;
- Assignment of variables: variable name = data;
- Operation of variables: put in a print statement for output or operation
There are three types of annotations in Java:
- single line comment
- multi-line comment
- Documentation Notes
type of data
Basic data types (8), also known as primitive data types:
reference data types (3): arrays, classes, interfaces
Type conversion:
- Automatic type conversion, also called implicit conversion
- Coercive type conversion, also called explicit conversion
operator
Operator: A special symbol used to represent data operations, assignments, and comparisons of numbers and integers
Operator classification: arithmetic operators, assignment operators, comparison operators, logical operators, ternary operators
1. Arithmetic operator
2. Assignment operator
3. Comparison operator
4. Logical operator
5. Ternary operator
Conditional expression b?x:y;
, first calculate the condition b, and then make a judgment. If the value of b is true, the value of x is calculated, and the result of the operation is the value of x; otherwise, the value of y is calculated, and the result of the operation is the value of y.
Java flow control statement
choose structure
if statement: if(条件表达式){ 一条或多条语句 };
if else statement: if(条件表达式) {语句块1} else {语句块2}
if multi-branch statement:
switch switch statement:
loop structure
In the program, when you want to do a certain work repeatedly, you can use the loop statement, including: for loop, while loop, do...while loop.
for loop statement:
while loop statement:
do...while loop statement:
Process jump
Process jump statement:break,continue
- break: end the case condition judgment in switch and end the loop in the loop body
- continue: acts in the loop body, ends the current loop of the loop body, and enters the next loop
array
An array is a collection of data, a container used to store any type of data, including primitive data types and reference data types, but once the type of the array is specified, it can only be used to store data of the specified type.
There are three ways to declare an array:
- datatype[] arrayname = new datatype[length];
- datatype[] arrayname = {data,data,...,data};
- datatype[] arrayname = new datatypelength[] {data,data,…,data};
One-dimensional array:
-
Array variable declaration:
syntax:数据类型[] 数组名;
, such as:int[] num;
,double[] d;
,String[] str;
-
The creation of array objects:
syntax:数组名 = new 数据类型[长度];
, such as:num = new int[4];
, the length of the array cannot be changed after declaring its length -
Assignment:
Syntax:数组名[下标] = 数据;
, such as: num[0] = 3; -
The use and traversal of array elements:
Syntax:数组名[下标]
, get the specified subscript is the data.
Two-dimensional array:
-
Array variable declaration:
syntax:数据类型[][] 数组名;
, such as:int[][] num;
,double[][] d;
,String[][] str;
-
The creation of array objects:
syntax:数组名 = new 数据类型[外长度][内长度];
, such as:num = new int[4][3];
, the length of the array cannot be changed after declaring its length -
Assignment:
Syntax:数组名[外下标][内下标] = 数据;
, such as: num[0][0]= 3; -
The use and traversal of array elements:
Syntax:数组名[外下标][内下标]
, get the specified subscript is the data.
Objects and Classes
Object: There are objective individuals that can be distinguished from each other, such as this car, this person, this house, this table, this plant, this check, this raincoat. In a nutshell: everything is an object.
Class: A group or abstraction of several objects with the same properties and behaviors. A class is a template for creating objects and consists of two parts: properties and behaviors
A class is a generalization or abstraction of an object, and an object is an instantiation of a class.
class declaration
[修饰符] class 类名{//类的声明部分
[成员变量]
[成员方法]
}
Declaration of member variables: [修饰符] 数据类型 变量名 [= 初始值];
Declaration of member method:
[修饰符] 返回值类型 方法名([数据类型 参数名,……]){
//方法体,该方法完成的功能代码
}
Constructor declaration:
[修饰符] 构造器名([数据类型 参数名,……]){
//构造器完成的功能代码
}
Note:
①The name of the constructor must be the same as the name of the class
②The constructor has no return value type
③Any class contains a constructor. If no class constructor is explicitly defined,
④ the system will provide a default no-argument constructor for the class. Once a constructor is explicitly defined in a class, the system no longer provides a default constructor for the class.
class usage
Declaration of class variables: 类名 对象名;
creation of class objects, assignment to variables: assignment of 对象名 = new 构造器([参数列表]);
object properties: 属性:对象名.属性名、对象名.属性名 = 数据;
invocation of properties and methods:属性:System.out.println(对象名.属性名);方法:对象名.方法名();
Member variables and local variables:
- Member variables: declared outside the body of the method in the class, can have default values, and can use modifiers. Scope: Entire class
- Local variables: declared in the method body or code block, have no default value, and can only be modified with final. Scope: the current method body
Parameters: The essence of parameters is a special local variable, which can only be defined in the parentheses of the method
overload
Overloading of methods: Multiple methods with the same method name but different parameters are defined in the same class
Overloading in the same class, with the same method name and different parameters (different number, order, and type of parameters)
overloading the constructor:
The return value type of the method:
- No return type: void,
return;//结束方法体
- There are return value types: data types (basic data types, reference data types),
return 数据;//结束方法体,并且返回一条数据
keywords
this keyword:
this is a special reference that points to the current object
Two ways of using this:
If there is a naming conflict between local variables and member variables, the member variables and local variables can be distinguished by the name of this.member variable.
A constructor needs to call another constructor of this class, which can be called by this() method, but this() must be written on the first line.
static keyword:
Static variables: Member variables modified with static are called static variables. The difference between static variables and non-static variables is: static variables are shared by all objects, and there is only one copy in memory, which is only when the class is first loaded. is initialized. Non-static variables are owned by the object and are initialized when the object is created. There are multiple copies, and the copies owned by each object do not affect each other. The initialization order of static member variables is initialized in the order in which they are defined.
Static method: A member method modified with static is called a static method. Static methods can be accessed without any object (for static methods, there is no this). Due to this feature, non-static classes of classes cannot be accessed in static methods. Member variables and non-static member methods, because non-static member methods/variables must depend on specific objects to be called.
Call format:类名.静态变量名 ,类名.静态方法名()
Static inner class (static modified class can only modify inner class): There is one biggest difference between static inner class and non-static inner class: non-static inner class will implicitly save a reference after compilation, the reference is to the enclosing class that created it, but the static inner class doesn't. The absence of this reference means: 1. Its creation is not dependent on the creation of the enclosing class. 2. It cannot use any non-static member variables and methods of the enclosing class.
Static code block:
It is a code block preceded by static, which is generally used to do some initialization work for the work of the class, such as initializing some static variables. There can be many static initializer blocks in a class, and they can appear anywhere in the class body. The runtime system guarantees that static initialization blocks are called in the order in which they appear in the source code
A static block can be used to optimize program performance: because it is only executed once when the class is loaded
super keyword:
super represents the parent class object,
Usage:
super.属性名、super.方法名();
used to call the instance variable of the same name hidden by the parent class
super([参数列表])
in the subclass Used to call the constructor of the parent class in the constructor of the subclass
The constructor of each subclass will provide a default super() without explicitly calling super(), and super() must be the first statement of the constructor
final keyword:
The final keyword, which means final, unmodifiable, and the most unchangeable, is used to modify classes, methods and variables, and has the following characteristics:
- Modified classes: classes cannot be inherited, and all member methods in final classes will be implicitly designated as final methods;
- Modifier variable: The variable is a constant. If it is a variable of basic data type, its value cannot be changed once it is initialized; if it is a variable of reference type, it cannot be allowed to point to another object after it is initialized .
- Modifier method: method cannot be overridden
Explanation: There are two reasons to use final methods. The first reason is to lock the method to prevent any inherited classes from changing its meaning; the second reason is efficiency. In earlier Java implementations, final methods were turned into inline calls. But if the method is too large, you may not see any performance gain from inlining calls (now Java versions don't need to use final methods for these optimizations). All private methods in a class are implicitly final.
Reference: https://gitee.com/SnailClimb/JavaGuide
Access modifiers
Access modifiers restrict access to member variables and member methods
Three Features of Java
package
Encapsulation refers to hiding the state information (attributes) of an object and does not allow external objects to directly access the internal information of the object (private implementation). But it is possible to provide some methods that can be accessed by the outside world to manipulate properties.
Make the member variables in the class private, and provide public get and set methods to control the access actions of attributes to ensure the security of operations on private attributes:
inherit
Inheritance extends: When the same attributes and behaviors exist in multiple classes, these contents are extracted into a single class, then multiple classes do not need to define these attributes and behaviors, just inherit the single class. Multiple classes can be called subclasses, and a single class is called a parent or superclass.
Basic syntax:
[修饰符] class 子类名 extends 父类名{
类体部分
}
Inheritance is a technique of creating a new class using the definition of an existing class as the basis. The definition of a new class can add new properties or methods (extend the parent class), or have the properties and methods of the parent class, and pass its own The method again implements the method of the parent class (overriding). By using inheritance, new classes can be created quickly, which can improve code reuse, program maintainability, save a lot of time for creating new classes, and improve our development efficiency.
Java only supports single inheritance, not multiple inheritance. A class can only have one parent class, not multiple parent classes. Java supports multiple layers of inheritance (inheritance hierarchy). Java inherits the non-private member variables and member methods of the parent class, but please note: the subclass cannot inherit the constructor of the parent class.
Note: Do not inherit only to obtain a function in other classes, there must be a belonging ("is a") relationship between classes
Method rewriting:
When an instance method inherited by a subclass from the parent class cannot meet the functional needs of the subclass, the instance method needs to be reimplemented in the subclass. This process is called rewriting, also known as overriding ,cover.
The premise of method rewriting: inheritance, the modifier of the subclass is greater than or equal to the parent class, the method name, parameter list, and return value type must be the same
polymorphism
Polymorphism: Multiple forms of a thing (the premise of polymorphism: inheritance, rewriting, upcasting)
Through polymorphism, code reusability can be improved and the coupling between modules can be reduced.
abstract class
The concept of abstract class:
A method without a method body can be defined in Java, and the concrete implementation of the method is completed by a subclass. This method is called an abstract method, and the class containing the abstract method is an abstract class. For example, the method of calculating the perimeter and area of the Shape class cannot be determined, so such a method can be declared as abstract so that it can be implemented in a concrete subclass.
Declaration of abstract class: Declaration of [修饰符] abstract class 类名 [extends 父类名]{类体}
abstract method: [修饰符] abstract 返回值类型 方法名([参数列表]);
Because abstract methods cannot determine the specific functions to be performed, all abstract methods have no method bodies, and semicolons need to be added after parentheses.
In addition to using abstract modification, abstract classes and ordinary classes are the same as ordinary classes. Similarly, abstract classes can have no abstract methods, but once a class has abstract methods, the class must be declared abstract.
The use of abstract classes:
Because abstract classes are not a concrete class, they cannot be instantiated, but abstract classes can be used to declare variables.
Abstract classes can be inherited, and all abstract methods of abstract classes are implemented in subclasses to achieve the abstract class. reified
interface
In Java, the interface is not only a "convention" in the process of program development, but also a more abstract abstract class.
Interface declaration syntax: [修饰符] interface 接口名{[常量];[抽象方法];}
Interface implementation syntax: [修饰符] class 类名 [extends 父类名] [implements 接口1,接口2,……]{类体部分}
A class can implement multiple interfaces, thus solving the shortcomings of Java's single inheritance.
The role of the interface:
- Improve program reusability
- Improve program scalability
- Reduce program coupling
- multiple inheritance