According to the online courses on station b and the relevant materials of Java, the relevant knowledge of Java is sorted out
catalogue
Integer variables and constants
Floating point variables and constants
Character variables and constants
Boolean type variables and constants
Assignment operator and extended assignment operator
Conditional operator (ternary operator)
9. Use Scanner to obtain keyboard input
Select structure (if..., then...)
Loop structure (if..., continue...)
2.break and continue statements
5. Garbage collection mechanism
8. Parameter value transfer mechanism
1. Basic knowledge of inheritance
2. Array initialization: static initialization, dynamic initialization and default initialization
Chapter I
1. Notes
- Single line comments: / / the following single lines are comments
- Multiline comment: / * * / comment between two * (cannot be nested)
- Document notes: / * * / between the second and third * are notes, which contain some explanatory text and JavaDoc tags
2. Identifier rules
- Function: used to name variables, classes, methods and packages
- Rules:
The identifier must begin with a letter, an underscore "-" and a dollar sign "$"
Other parts of the identifier can be any combination of letters, underscore "-", dollar sign "$" and numbers
Java is case sensitive but unlimited in length
Identifier cannot be a keyword
- standard:
The identifier of the class name should be capitalized as much as possible (or not)
Identifiers representing methods and variables. The first word is lowercase and the second word is uppercase (e.g. eatFood())
Variables can be Chinese characters, but not recommended (int age = 18; / / yes)
Keywords / reserved words
abstract | assert | boolean | break | byte | case | catch | char | class |
continue | default | do | double | else | extends | final | finally | float |
goto | if | implements | import | instanceof | int | interface | long | native |
null | package | private | protected | public | return | short | static | strictfp |
switch | synchronized | this | throw | throws | transient | try | void | volatil |
const | for | new | super |
4. Variables
- Essence:
Represents an "operable storage space". The location is determined, but the content is uncertain. The space can be accessed by accessing the variable name to manipulate the space.
- Declaration of variables
Each variable must declare a data type, which determines the storage space of the variable.
Variable elements include variable name, variable name and scope. (such as int a;)
Precautions
Each variable has a type, which can be either a basic type or a reference type
Variable name must be a legal identifier
Variable declaration is a complete statement, so each declaration must end with a semicolon
- Classification of variables
Local variable: a variable defined in a method or statement block. From the declared position to the end of the method or statement execution (must be initialized)
Member variables: variables defined outside the method and inside the class. Subordinate to the object, the life cycle is always accompanied by the object. (it can be assigned manually or initialized automatically)
Static variables: defined using static. Subordinate to the class, the life cycle (the longest of the three) is always accompanied by the class, from class loading to unloading.
5. Constant
It usually refers to a fixed value, such as 1, 2, 3, a, b, c, true and false
In Java, the keyword final is mainly used to define constants, which are called symbolic constants. Once initialized, the value cannot be changed
6. Basic data type
Numeric type (integer, floating point): byte (1 byte), short (2 bytes), int (4 bytes), long (8 bytes), float (4 bytes), double (8 bytes)
Character type: char (2 bytes)
boolean: boolean (1-bit)
-
Integer variables and constants
Variables: byte (1 byte) [- 128-127], short (2 bytes) [- 32768-32767], int (4 bytes) [- 2147483648-2147483647], long (8 bytes)
Constant: decimal number: e.g. 2, 3, 4, 60700
Octal number: "0" starts, such as 015
Hexadecimal number: starting with "0x", such as 0x15
Binary number: starting with "0b", such as 0b0111011
Note: Java's integer constant is of type int by default. Declaring long type usually adds "L" or "L", such as 55555l
-
Floating point variables and constants
Variables: float (4 bytes) [accurate to 7 significant digits], double (8 bytes)
Constant: decimal: 3.14, 4.56
Scientific counting method: 314e2, 314e-2
Note: the default constant is double, and the declared float type should be added with "F" or "F", such as 3.14f
Floating point type is imprecise and should not be used for comparison!!
If you want to compare, you can use Java Math under the two classes: BigInteger to achieve arbitrary precision integer operation, GigDecimal to achieve arbitrary precision floating-point operation.
For example: gigdecimal a = gigdecimal valueOf(1.0/10.0);// Will get accurate results
-
Character variables and constants
Variable: char (2 bytes)
Used to represent characters in the Unicode encoding table
Escape character:
Escape character | meaning |
\b | Back off |
\n | Line feed |
\r | enter |
\t | Tab |
\ " | Double quotation mark |
\ ' | Single quotation mark |
\\ | Backslash |
Note: the String type is a character sequence
-
Boolean type variables and constants
Constants: true, false
Note: unlike C, 0 or non-0 integers cannot be substituted
In if, if (man) is equivalent to man==true
7. Type conversion
-
Automatic type conversion
Data types with small capacity are automatically converted to data types with large data volume (i.e. conversion from small range to large range)
public class test{ public static void main(String[] args){ int a=324; long b=a; double d=a;//Can be automatically converted System.out.println(b);//Output 324 System.out.println(d);//Output 324.0 //a=b; Automatic conversion is not allowed //long e=3.23; Cannot convert float f=234323L;//Can be automatically converted System.out.println(f);//Output 234323.0 //byte b2=1230; It exceeds the representation range and cannot be converted } }
-
Cast type
Syntax format: (data type) variable
public class test{ public static void main(String[] args){ double x=3.14; int y=(int)x; char c='a'; int d=c+1; System.out.println(y);//Output 3 System.out.println(d);//Output 98 System.out.println((char)d);//Output b } }
Pay attention to data overflow
8. Operator
Arithmetic operator (+ - * /% + + -), assignment operator (=), extension operator (+ = - = * = / =), relational operator (> < > = < =! =), logical operator (& & |! ^), bit operator (&| ^ ~ > < > > > > > > > >), conditional operator (?), string connector (+)
-
Arithmetic operator
Binary operator:
Operators with left and right operands are binary operators
Binary operators do integer operations: one is Long and the result is Long; If there is no Long, the result is int
Binary operators do floating-point operations: one is double, and the result is also double; Both operands are float and the result is float
Binary operators do remainder operations: operands can be integer and floating-point, and the result is remainder
Unary operator: + +: self increment++ a: Self increment before assignment; A + +: assign value first and then increase automatically
--: self subtraction-- a: Self subtraction before assignment; A --: assignment first and then self subtraction
For example: a=10++ a; b=a; Result b=11,a=11
a=10; a++; b=a; Results b=11,a=10
-
Assignment operator and extended assignment operator
"=" is the assignment operator: a=3 assigns 3 to a;
Extension operators: + =, - =, * =, / = for example, a+=b is equivalent to a=a+b; Others are similar; a*=b+3 is equivalent to a=a*(b+3)
-
Relational operator
>, <, > =, < =, = (equal to)= (not equal to)
The first four are only for numerical operation and char operation, and the last two are applicable
-
Logical operator
The operand and result are Boolean
operator | explain | |
Logic and | & | The left and right operands are true, the result is true, and the responsibility is false |
Logical or | | | If one of the left and right operands is true, the result is true |
Short circuit and | && | As long as one is false, return false directly |
Short circuit or | || | As long as one is true, return true directly |
Logical non | ! | ! False is true,! True is false |
Logical XOR | ^ | If the left and right operands are the same, it is false, but the difference is true |
At the same time, the operator ^, & ^, \
The short circuit operator is calculated from left to right. If the value on the left can determine the result, the result will be returned directly to improve efficiency
-
Bitwise Operators
Refers to binary operations
Bitwise Operators | explain |
~ | Reverse |
& | Bitwise AND |
| | Bitwise OR |
^ | Bitwise XOR |
<< | Shift left operator, which is equivalent to multiplying by two |
>> | Shift right operator, equivalent to dividing by two |
-
String connector
"+"
public class test { public static void main(String[] args) { String a="3"; int b=4; int c=5; System.out.println(a+b);//Output 34 System.out.println(a+c);//Output 35 System.out.println(a+b+c);//Output 345 } }
-
Conditional operator (ternary operator)
Syntax format: x? y: z (where x is Boolean type. If x is true, y will be returned, otherwise z will be returned)
public class test{ public static void main(String[]args){ int score =80; String type=score>60?"pass":"fail,"; System.out.println(type);//Output pass } }
Operator priority
Logical non > logical and > logical or
Parentheses can be used to make it easier to organize
9. Use Scanner to obtain keyboard input
import java.util.Scanner; public class test{ public static main(String[] args){ Scanner scanner=new Scanner(System.in); System.out.println("Please enter your name"); String name=scanner.nextLine(); System.out.println("Please enter your hobbies"); String favor=scanner.nextLine(); System.out.println("Please enter your age"); String age=scanner.nextInt(); System.out.println(name); System.out.println(age); System.out.println(favor); } }
Chapter II
1. Control statement
A statement used to control the execution order of statements in a program. There are sequential structure, selective structure and cyclic structure
-
Select structure (if..., then...)
If single choice structure {if (Boolean expression) {statement block}
public class test{ public static void main(String[] args){ double d=Math.random();//Generate random numbers between 0 and 1 System.out.println(d); int a=(int)(6*Math.random()+1);//Generate random numbers between 1 and 6 System.out.println(a); if(a<=3) {System.out.println("Small");} } }
If else double selection structure
public class test { public static void main(String[]args){ double d=Math.random(); System.out.println(d); int a=(int)(6*Math.random()+1);//Generate random numbers between 1 and 6 System.out.println(a); if(a<=3) {System.out.println("Small");} else {System.out.println("large");} } }
If else if else multiple selection structure
public class test { public static void main(String[]args){ double d=Math.random(); System.out.println(d); int a=(int)(6*Math.random()+1);//Generate random numbers between 1 and 6 System.out.println(a); if(a<=3) {System.out.println("Small");} else if(a==4) {System.out.println("a=4");} else//a> 4. Situation {System.out.println("large");} } }
switch structure (used to judge the situation of multiple values)
Switch (expression)
{
case value 1: statement 1; break;// The value is an integer or string, and break indicates the end of the statement
case value 2: Statement 2; break;
.......................................;
case value n: statement n; break;
default: statement; break;
}
public class test01 { public static void main(String[]args){ double d=Math.random(); System.out.println(d); int a=(int)(6*Math.random()+1);//Generate random numbers between 1 and 6 System.out.println(a); switch(a) { case 1:System.out.println("a=1");break; case 2:System.out.println("a=2");break; case 3:System.out.println("a=3");break; case 4:System.out.println("a=4");break; case 5:System.out.println("a=5");break; case 6:System.out.println("a=6");break; default:System.out.println("Not in the range of 1 to 6");break; } } }
-
Loop structure (if..., continue...)
while loop: loop first and then judge
Syntax: while (Boolean expression)
{
Circulatory body
}
public class test01 { public static void main(String[]args){ int a=0; int sum=0; while(a<=50) { sum+=a; a++; } System.out.println(sum);//Calculate 1 + 2 + 3 + 3 ++ 50, output 1275 } }
The do while loop is executed before judgment
public class test01 { public static void main(String[]args){ //Calculate 1 + 2 + 3 + 3 ++ fifty int a=0; int sum=0; do { sum+=a; a++; }while(a<=50); System.out.println(sum);Output 1275 } }
for loop
public class test01 { public static void main(String[]args){ //Calculate 1 + 2 + 3 + 3 ++ fifty int sum=0; for(int i=0;i<=50;i++) { sum+=i; } System.out.println(sum);Output 1275 } }
Nested loop
Set another cycle in one cycle
public class test01 { public static void main(String[]args){ //Calculate 1 + 2 + 3 + 3 ++ fifty int sum=0; for(int i=1;i<=5;i++) { for(int j=1;j<=5;j++) { System.out.print(" "+j); } System.out.print('\n'); } } }
The output result is:
Example: output 99 multiplication table
public class test { public static void main(String[]args){ int sum=0; for(int i=1;i<=9;i++) { for(int j=1;j<=9;j++) { if(j<=i) { sum=j*i; System.out.print(j+"*"+i+"="+sum+" "); } } System.out.println(); } } }
The output result is:
2.break and continue statements
break is used to forcibly exit the loop without executing the remaining statements in the loop
continue means to terminate this cycle and proceed to the next cycle
Tagged break and continue statements
A label is an identifier followed by a colon, such as "label:"
Function: we hope to nest another loop in one loop. Because the break and continue keywords usually only interrupt the current loop, if they are used with the tag, they will exist in the tag of the terminal.
public class test { public static void main(String[] args) { outer:for(int i=101;i<150;i++) { for(int j=2;j<i/2;j++) { if(i%j==0) { continue outer;//Return directly to the external loop where i is located } } System.out.print(i+" ");//Outputs a prime number between 101 and 150 } } }
3. Method
Statement block: the block determines the scope of local variables. The program code in the block, as a whole, should be executed together.
Method: it is a code fragment used to complete specific functions, similar to functions in other languages.
1. Method declaration format: [modifier 1, Modifier 2,......] Return value type: {method name (formal parameter list) {Java statement;...}
2. Method call format: object name Method name (argument list)
Formal parameter: used to receive incoming data when declaring a method
Argument: the data actually passed to the method when the method is called
Return value: the method returns the data of the environment calling it after execution
Return value type: the data type of the return value agreed in advance. If there is no return value, the return value type must be void
public class test02 { public static void main(String[] args) { test02 tm=new test02(); tm.print(); int c=tm.add(3, 40, 5)+20; System.out.println(c); tm.add1(30, 40); } void print() { System.out.println("Learning makes me happy!"); System.out.println("Study enriches me!"); } int add(int a,int b,int c) { int sum=a+b+c; System.out.println(sum); return sum;//return ends the program and returns sum } void add1(int a1,int b1) { int num=a1+b1; System.out.println(num); } }
be careful:
1. The number, data type, and order of the arguments must match the parameter list of the called method
2.return statementterminates the operation of a method and specifies the data to be returned
3. When passing parameters in method calls in Java, follow the principle of value passing (all passed are copies of data)
4. The basic data type passes the copy value of the data
5. The reference type passes the copy value referenced by the object, but points to the same object
4. Overloading of methods
Methods with the same name but completely different (parameter type, number of parameters and order of parameters are different)
Note: different return values and parameter names will not constitute method overloading
5. recursive algorithm
Basic idea: call yourself
For example, the following code will output countless a's
public class test02 { public static void main(String[] args) { a(); } static void a() { System.out.println("a"); a(); } }
Recursive structure includes: recursive header (the condition for the end of recursion) and recursive body (when to call its own method)
The above code can only output 5 a's
Example:
Factorial 10!
public class test02 { public static void main(String[] args) { System.out.println(a(10)); } static long a(int n) { if(n==1) { return 1; } else return n*a(n-1); } }
Chapter III
1. Objects and classes
The class is class, and the object is object and instance
public class student { int id; String name; int age; void study() { System.out.println("I'm studying hard!"); } void play() { System.out.println("I was playing games!"); } //The entry of program execution must have public static void main(String[] args) { student s=new student(); s.play(); } }
2. Typical class
public class student { int id; String name; int age; computer c; void study() { System.out.println("I'm studying hard!"+"use"+c.brand); } void play() { System.out.println("I was playing games!"); } //The entry of program execution must have public static void main(String[] args) { student s=new student();//Create an object s.name="Zhang San"; s.age=18; s.id=123456; computer c1=new computer(); c1.brand="association"; s.c=c1; s.study(); s.play(); } } class computer{ String brand; }
3. Memory analysis
It is divided into three areas: stack, heap and method area
1. Stack
Stack describes the memory model of method execution. Each method called will create a stack frame (storing local variables, operands and method exits)
The JVM creates a stack for each thread, which is used to store the information of the method executed by the thread (actual parameters, local variables)
The stack is thread private and cannot be shared between threads
The storage characteristics of stack are first in first out, last in first out
Stack is automatically allocated by the system, which is fast. Stack is a continuous memory space
2. Reactor
Heap is used to store created objects and arrays (arrays are also objects)
The JVM has only one heap, which is shared by all threads
Heap is a discontinuous memory space with flexible allocation and slow speed
3. Method area
The JVM has only one method area, which is shared by all threads
The method area is actually a heap, which is only used to store information related to classes and constants
It is used to store the permanent or unique content in the program
From the previous procedure:
4. Construction method
Used for object initialization
Key points: 1 Using the new keyword
2. Although the constructor has a return value, it cannot define the return value type (the return value type must be this class), and a return value cannot be used in the constructor
3. If we do not define a constructor, the compiler will automatically define a parameterless constructor. If it is defined, the compiler will not automatically add it
4. The constructor's method name must be consistent with the class name
class point { double x,y; public point(double m_x,double m_y) { x=m_x; y=m_y; } public double getdistance(point p) { return Math.sqrt((x-p.x)*(x-p.x)+(y-p.y)*(y-p.y));//Calculate the distance between two points } } class test{ public static void main(String[] args) { point p=new point(3.0,4.0); point p1=new point(0.0,0.0); System.out.println(p.getdistance(p1)); } }
Overloading of construction methods
5. Garbage collection mechanism
Function: 1 Useless objects found
2. Reclaim memory space occupied by useless objects
Related algorithms:
1. Citation counting method
Each object in the heap has a reference count. If it is referenced once, the count increases by 1. If the value of the referenced variable becomes ULL, the count decreases by 1 until the count is 0, indicating that there are no objects.
2. Citation reachability method
The program regards all reference relationships as a graph. Starting from a node GC ROOT, it looks for the corresponding reference node. After finding this node, it continues to look for the reference node of this node. When all reference nodes are found, the remaining nodes are considered as unreferenced nodes, that is, useless nodes.
6. Essence of this
The essence is "the address of the created object". Since the object has been created before the construction method is called, this can also be used to represent the "current object" in the construction method.
public class testthis { int a,b,c; testthis(int a,int b){ this.a=a; this.b=b; } testthis(int a,int b,int c){ this(a,b);//Call construction method this.c=c; } void sing() { System.out.println("sing"); } void eat() { this.sing(); System.out.println("Go home for dinner!"); } public static void main(String[] args) { testthis s=new testthis(2,3); System.out.println(s.a); System.out.println(s.b); System.out.println(s.c); s.eat(); } }
this cannot be used in static methods
7.static keyword
In a class, the member variables declared with static are static member variables, also known as class variables. The life cycle of class variables is the same as that of the class and is valid during the execution of the whole application.
Member variables and methods modified by static are subordinate to classes, while ordinary variables and methods are subordinate to objects.
Shared by all objects of the class
Can be called by class name and object name
static access:
Static and non member variables and methods
Static member methods can only access static member variables and methods
Static initialization block
For example: static{
System.out.println("output");
}
8. Parameter value transfer mechanism
The basic data type value passes a copy of the value
The value passed by the reference type is the copy passed, but the reference points to the address. Both the copy and the original parameter point to an address. Therefore, changing the value of the address pointed by the copy means changing the value of the object pointed by the original parameter.
9.Java package mechanism
Package mechanism is an important means of managing classes in Java. During development, we will encounter a large number of classes with the same name. Through package, we can easily solve the problem of class name duplication, and also realize the effective management of classes. Package for classes is equivalent to folder for files.
1. It is usually the first non annotative statement of the class
2. Package name: the domain name can be written upside down, plus the module name, which is convenient for internal management.
10.import import class
Java will import Java by default Lang package, so we can call these classes directly
If you import two classes with the same name, you can only use package class + class name to display the relevant classes called
Chapter IV
Three characteristics of object-oriented: inheritance, encapsulation and polymorphism
1. inherit
1. Basic knowledge of inheritance
public class testexend { public static void main(String[] args) { student s= new student(); s.name="Zhang San"; s.age=20; s.school="university"; } } class person{ String name; int age; public void rest() { System.out.println("Take an hour off!"); } } class student extends person{//student inherits the members of the person class String school; public void study() { System.out.println("Study for an hour!"); } }
Key points: 1 Parent classes are also called superclasses, base classes, and derived classes
2. In Java, there is only single inheritance, not multiple inheritance
3. There is no multi inheritance in Java classes, and there is multi inheritance in interfaces
4. The subclass inherits from the parent class and can get all the properties and methods of the parent class (except the construction method of the parent class), but it may not be directly accessible (such as private)
5. If you define a class without calling extends, its parent class is Java lang.Object
instanceof is a binary operator. On the left is an object and on the right is a class. If the object is an object created by a class or subclass on the right, the return value is true.
public class testexend { public static void main(String[] args) { student s= new student(); s.name="Zhang San"; s.age=20; s.school="university"; s.rest(); s.study(); System.out.println(s instanceof student); System.out.println(s instanceof person); System.out.println(s instanceof Object); } } class person{ String name; int age; public void rest() { System.out.println("Take an hour off!"); } } class student extends person{ String school; public void study() { System.out.println("Study for an hour!"); } }
2. Method rewriting
By overriding the method of the parent class, a subclass can replace the behavior of the parent class with its own behavior.
Key points: 1 "= =": the method name and parameter list are the same
2. "< =": return value type and declared exception type, subclass less than or equal to parent class
3. "> =": access permission. The subclass is greater than or equal to the parent class
public class testoverride { public static void main(String[]args) { son s=new son(); s.work();//Override the work method of the parent class } } class father{ public void work() { System.out.println("Work for a while"); } public father play() { return new father(); } } class son extends father{ public void work() { System.out.println("Stop working"); } public son play() { return new son();//The return value type is less than or equal to the type of the parent class } }
3.Object class
toString method: the source code is:
public String toString(){ return getClass().getName()+"@"+Tnteger.toHexString(hashCode()); }
Rewrite:
public class testobject { public static void main(String[] args) { testobject to=new testobject(); System.out.println(to.toString());//The output is similar: testobject@515f550a person p=new person(); p.name="Zhang San"; p.age=19; System.out.println(p.toString()); } public String toString() { return "rewrite"; } } class person{ String name; int age; public String toString() { return name+"Age:"+age; } }
equals method: the source code is:
public boolean equals(Object obj){ return (this == obj); }
public class testequals { public static void main(String[] args) { person t1 = new person(67890,"Wang Wu"); person t2 = new person(12345,"Li Si"); System.out.println(t1==t2); System.out.println(t1.equals(t2)); } } class person{ int id; String name; public person(int id,String name) { this.id=id; this.name=name; } }
Rewrite:
import java.util.Objects; public class testequals { public static void main(String[] args) { person t1 = new person(12345,"Wang Wu"); person t2 = new person(12345,"Li Si"); System.out.println(t1==t2); System.out.println(t1.equals(t2)); } } class person{ int id; String name; public person(int id,String name) { this.id=id; this.name=name; } @Override public int hashCode() { return Objects.hash(id); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; person other = (person) obj; return id == other.id; } }
Right click - source - as shown in the figure, which can automatically generate rewrites according to the selection
Super is a direct reference to the parent class object. You can access the methods or properties in the parent class that are overridden by the child class through super
public class testsuper { public static void main(String[] args) { //father f=new father(); son s=new son(); s.f(); } } class father{ public int num; public void f() { num=100; System.out.println("father.num="+num); } } class son extends father{ public int num; public void f() { num=200; System.out.println(num);//Output 200 super.f();//Call the normal method of the parent object and output father num=100 System.out.println(super.num);//Call the normal method of the parent object and output 100 System.out.println("son.num="+num);//Output son num=200 } }
Inheritance tree tracing
The first sentence of the construction method is always: super (...) To call the construction method of the parent class. Therefore, the process is: first trace back to Object, and then execute the initialization block and construction method of the class downward until the current subclass is known.
2. encapsulation
Access control character
Modifier | Same class | Same package | Subclass | All classes |
private | √ | × | × | × |
default | √ | √ | × | × |
protected | √ | √ | √ | × |
public | √ | √ | √ | √ |
Private: it means private and can only be accessed by yourself
default: indicates that there is no modifier, and only classes of the same package can access it
protected: indicates that it can be accessed by classes of the same package and subclasses of other packages
public: can be accessed by all classes in all packages of the project
Key points: 1 Class properties are generally private
2. Provide corresponding set and get methods to access relevant properties
3. Some auxiliary methods that are only applicable to this class can be modified with private
3. Polymorphism
It refers to the same method call, which may have different behaviors due to different objects.
Key points: 1 Polymorphism is the polymorphism of methods, not attributes (polymorphism has nothing to do with attributes)
2. There are three necessary conditions for polymorphism: inheritance, method rewriting, and parent class reference pointing to child class objects
3. After the parent class reference points to the child class object, call the method overridden by the child class with the parent class reference. At this time, polymorphism appears.
public class testpolyme { public static void main(String[] args) { animalaa(new animal()); animalaa(new dog()); animalaa(new cat()); } static void animalaa(animal a) { a.shout(); } } class animal{ public void shout() { System.out.println("Let out a cry"); } } class dog extends animal{ public void shout() { System.out.println("Woof, woof"); } } class cat extends animal{ public void shout() { System.out.println("cat "); } }
Object transformation
animal d=new dog(); Convert dog to animal class, and now D is animal class
dog d2=(dog)d; Convert dog of animal class to dog class
finall keyword
1. Modified variable: the variable modified by it cannot be changed. Once a value is assigned, it cannot be re assigned
2. Modification method: this method cannot be overridden by subclasses, but can be overloaded
3. Modified class: modified classes cannot be inherited
Chapter VII
1. Concept of array
An array is an ordered collection of data of the same type, and each element can be accessed by subscript
Features: 1 The length is definite
2. Elements must be of the same type
3. The data type can be any data type
Arrays are objects
Declaration of array: type[] name or type name [];
2. Array initialization: static initialization, dynamic initialization and default initialization
public class test01 { public static void main(String[] args) { //initiate static int[] a= {2,3,5}; user[] b= { new user("Zhang San",10), new user("Li Si",20), new user("Wang Wu",30), }; //Default initialization int[] c=new int [3];//Assign values to elements by default //dynamic initialization int [] d=new int[2]; d[0]=3; d[1]=9; } } class user{ public String name; public int age; user(String name,int age){ this.name=name; this.age=age; } }
3. Traversal of array
Traversal: initial and read
foreach loop, which is used to read the value of array elements. The value of elements cannot be modified
package cn.dd; public class test03 { public static void main(String[] args) { int[]a=new int[4]; for(int i=0;i<a.length;i++) { a[i]=2*i; } for(int i=0;i<a.length;i++) { System.out.println(a[i]); } //foreach loop, which is used to read the value of array elements. The value of elements cannot be modified for(int m:a) { System.out.println(m); } } }