#@TOC
The following knowledge is taught by Mr. Zhong Jian
JAVA first class
1, Course objectives
Complete the first Java code
- 1. General development of programming language: three front-end JavaScript frameworks (Vue, react, angular) and server-side JAVA
+Linux python
2. Understanding of JAVA
Sun (Oracle) | MS | |
---|---|---|
Web Services | Apache Tomcat | IIS |
frame | SSM | SSH |
Web development | JSP | Asp, Asp.net |
Development platform compiler + Library | J2SE,J2EE,J2ME *Kotlin | .net framwork |
development language | JAVA | C#,J#,VB.NET,C++.NET... |
database | Oracle,sqlite,Mongodb,mySql ,Redis | SQL server , Access |
Question 1: the difference between J2SE java and J2EE Java Web
The libraries have different application backgrounds, and J2EE is mainly JSP Java -- > java web (servlet filter) - > SSH and SSM
Question 2: JDK JRE differences
JRE operating environment - user; The JDK development environment has javac - programmers
Question 3: Java architecture
Cross platform compile once and run everywhere. virtual machine
- Compile and use javac to turn the source code into class (bytecode) = = exe (static procedure)
- Explain the execution of running bytecode on a Java virtual machine (JVM) using java commands (dynamic process)
Question 4: what type of language is Java
None of them. The first stage is compilation, and the second stage is interpretation and operation
Question 5: the difference between compiler and editor (IDE)
Compiler is to compile the source code into the code that the computer can execute;
Editor: an integrated development environment to improve development efficiency.
clang g++ gcc
2, JAVA installation and operation
1. Software needed to run Java
What ides do you choose? 1 ,Eclipse ,NetBeans ,intelij Ideal
Compiler JAVA JDK JRE
http://www.java.com Java SE 8u
https://netbeans.org/ Older releases https://netbeans.org/downloads/old/8.2/
2. Environmental variables
1) What are environment variables and variables used by the operating system
It is required that the system can recognize the command Java at any location Exe (execute Java commands), javac Exe (command to compile java code)
How to set: add a path P to the system variable
2) Setting of environment variables
3. Write the first Hello world!
System.out.println() System.out.print()
A. Setting up netbeans environment to simplify code writing
B. The only basic unit of code composition in JAVA is class
C. Multiple classes are allowed in the same java file. However, there can only be one public class, which is called the main class in the java file.
The file name must be consistent with the main class name.
When a main class contains the main method, the main class becomes the main class of the whole project (that is, the entry of the program).
D. One class generates one Class bytecode file
public class Exam1 { public static void main(String[] args) { System.out.println("HelloWorld"); } }
Second class
Course objectives
- Understand the structure of java code
- Understand the compilation and running steps of Java
- Understand JAVA virtual machine JVM
- Java basic programming
1, Compilation and running of Java code
Manual compilation and running of code:
Java source code - javac Exe - > bytecode file [*. class] - > java Exe execution code
Compilation (static) interpretation execution (dynamic)
Question: Why are there bytecode files?
Bytecode who recognizes and runs it JVM compiles once and runs everywhere!!! -- Cross platform
Question: what is the role of the JVM?
1 cross platform 2 Safe and convenient maintenance
2, java code structure
public int main(String[] args){ // This is allowed in C + +, but it is wrong in Java. cout<<"helloworld"<<endl; } class Student{ } struct
The first level code of C/C + + can be a function class structure diagram... But Java can only be a class.
Be sure to understand what is first level code!!! Be sure to know that the specific code is written in the method, and the method is written in the class
(java code consists of several classes)
- There can be multiple classes in a file, but there can only be one public class
-The file name is the same as the public class name - Capitalize the first letter of the class name
- Class is generally divided into two parts: properties and methods
- Code formatting shortcut alt+shift + f
3, Write a student information code
A class StuM contains the main method as the main class (test class)
Create a Student class
public class Student { public String sNo; public String sName; public Student(String sNo, String sName) { this.sNo = sNo; this.sName = sName; } @Override //Don't worry about this keyword for the time being. It is automatically generated by the system -- (as will be discussed later, here is the declaration method) (write) public String toString() { return "Student information{" + "Student number:" + sNo + ", full name:" + sName + '}'; } }
summary
This class mainly needs to master
- Understand the role of virtual machines
JVM is the core of the whole Java. - How to use NetBeans to create a class (Student)
- Class contains properties and methods (functions). There is a special method constructor (initializing properties)
When writing attribute code in NetBeans, you can right-click – > code generation to automatically generate construction methods and toString()
Special method [system. Out. Println (object) / / automatically call object. toString()] - The main class that contains the main method is also called the test class. General test classes are used as users, programmers
The code is usually written in other classes.
Third class
Course objectives
Introduction to the basics of java: Circular judgment of data type keywords
1, Data type
int x; int - data type X - variable; 12 is the shaping constant 12.5 double precision constant
Question:
(1) Native data type (basic data type, built-in data type)
Integer: (1) byte (2) short (4) int (8) long
Floating point number: (8)float (8)double
Character: (2) char
Logic: boolean true false
(2) Reference data type
String str = new String("abcd");
Student stu=new Student(123456,18);
Student stuA=stu;
byte x; -128- 127
int x=12;
int y=x;
1. What is the function of data type? int x
Tell the compiler how much storage space variables have!!!
2. Is int (variable type declaration is required)?
not always! var x=12.5 the compiler can automatically infer the variable type according to the assignment
3. Do different languages have the same data type (also different)?
- Native data type: build in built-in data type
(1) Integer int 32 bits, long 64,short 16,
(2) Floating point number float double char 16 bits
(3) Character byte 8 bits
(4) Logical boolean - Reference data type
Student stu ;// Stu – object variable student – data type class · type
stu =new Student();
new functions: A. calculate the memory size, B. create the memory to hold, C. call the construction method.
class Student{ int age; float score; public void print(){} } Student stu=new Student() ;//The stu object variable stu is an instance relative to the Student class int x[] //Array variable
4. Why int x; Why does Student stu=new Student() need new
int x; x=12;
Student stu ;
stu.println();
All compilers that do not know the memory size need new
long x[ ]=new long [10];
x[0]=12;
Student stus[ ]=new Student [10];
stus[0] = new Student(121213,18);
int double float . . . How to type convert with String
Packaging (packaging) 1 Assigning the value of int to Integer is called boxing; 2. Assigning the value of Integer to int is called unpacking
int – > Integer byte -->Byte
double --> Double
float --> Float
2, Type conversion and trap (PIT)
- Convert from small data type to large data type (default); Converting from a large data type to a small data type requires a mandatory type description (int)
- The default numeric constants with decimals are double, and float x=12.5 is wrong
Float x = (float) 12.5 or float x=12.5f
short y= 12; - Tip: number x to character "" + X / / empty string + X
- Logical short circuit judgment
a<b && ++i >0 a>b || ++i //a=10 b=9; - Standard input, standard output
cout cin is displayed to the command line through command line input (keyboard), which is called standard output
Three classroom exercises
- Write code and complete 1 ++ one hundred
- Calculate 1 + according to the keyboard input n+ Value of n
public static void main(String[] args) { System.out.print("Please enter n:"); Scanner sc=new Scanner(System.in); int n=sc.nextInt(); int sum = 0 ; for (int i = 0 ; i < n+ 1 ; i++) { //alt +shift +F sum+=i; } System.out.println(sum); }
task
//1. Simulated change
//Currency denomination 50 20 10 5 1
//Input a number within 200 from the keyboard and output the type and number of currency
126 50 ( 2 ) 20 ( 1 ) 5 ( 1 ) 1 ( 1 )
//3. Fibonacci number
The fourth class
I Classroom practice
1. Output Greek letters (purpose: Master type conversion)
//Method 1 char chA = 'α'; char chB = 'ω'; int iStartUnicode = chA; int iEndUnicode = chB + 1 ; for (int i = iStartUnicode; i < iEndUnicode; i++) { System.out.print((char) (i)); if((i-iStartUnicode+ 1 ) % 10 == 0 ) System.out.println(""); //Method 2 System.out.println("Greek alphabet:"); for (char i = 'α'; i <= 'ω'; ++i) { char g; g = (char) i; System.out.print(" " + g); } //Method 3 System.out.println("Greek alphabet:"); char chBegin = 'α'; char chEnd = 'ω'; int i = 0 ; while (true) { char ch = (char) (chBegin + i); System.out.print(ch + " "); if (ch == chEnd) { break; } ++i; } //The time complexity O(n) of the algorithm is evaluated by the following method double start = System.currentTimeMillis(); //coding double end = System.currentTimeMillis(); System.out.print("Algorithm time:+ (end-start));
2, Course objectives
Master array
-
One dimensional array
-
Two dimensional array
(1) One dimensional array
1. Declaration and creation
Class exercises declare a one-dimensional array with a size of 5;
Realization: A. assignment; b. Copy the data in array a to array b; C. Sort array b
int a[]={ 1 , 2 , 3 , 4 , 5 , 6 }; //Direct assignment int b[]=new int[ 5 ]; b=Arrays.copy(a,a.length);// Array copy b=Arrays.sort(a);//Array sorting
Note: the sorting rule must be specified for array sorting. When the elements in array a are of native data type, the default sorting is
Small to large.
However, if the elements in the array are of reference data type (such as Student a[] =new Student[5]), the sorting must be specified
Rules.
b=arrays.copy(a,5);
??? b[0]==a[0];
Knowledge points: shallow copy and deep copy (serialization)
2. Random number
[small, large] formula of random number = (int) ((large small) * math Random () + small)
-10 10
- For statement and for each statement with frequent errors
- For statement for assignment;
- The for each statement can only be used to traverse values
Arrays.sort(a) / / array sorting
#### //Think about why the following code is wrong!!! public static void main(String[] args) { Student a[] = new Student[ 5 ]; int b[]; for (Student e : a) { // Name and grade (random number) e = new Student("Xiao Wang" , (int) (Math.random() * 30 ));//Call constructor new Student object } for (int i = 0 ; i < a.length; i++) { System.out.print(a[i]+ " "); } }
- Array sorting
###(2) Two dimensional array
1. Memory model*
( 1 ). Understand why you can't use for each to assign values (initialize reference type array)
( 2 ). Shallow copy and deep copy (they are very complex and can be processed quickly through file serialization)
( 3 ). Understanding multidimensional arrays
Declaration of two-dimensional array
(1) Static initialization
int intArray[][] = { {1,2} , {2,3} , {3,4,5} };
(2) Dynamic initialization
Starting from the highest dimension, allocate space for each dimension:
Student stus[]=new Student[ 10 ]; Student stuss[][]== new Student[ 5 ][]; stuss[ 0 ]=new Student[ 5 ]; stuss[ 0 ][ 3 ]=new Student( 123 ,"Zhang San", 18 ); stuss[ 1 ]=new Student[ 3 ]; stuss.length=? stuss[ 1 ].length=? for(int i= 0 ;i<stuss.length;++i){ for(int j= 0 ;j<stuss[i].length;++j){ System.out.println(stuss[i][j]); } }
arrayName = new type[5];
arrayName[0] = new type[3];
arrayName[1] = new type[2];
Int - > wrapper class Integer
//Two dimensional array connection //Objective: to understand the multi-dimensional array model and the creation of two-dimensional array public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int arr[][] = new int[n][]; //Create array for (int i = 0 ; i < arr.length; i++) { arr[i]=new int[i+ 1 ]; } //assignment for (int i = 0 ; i < arr.length; i++) { for (int j = 0 ; j < arr[i].length; j++) { arr[i][j]=(int) (Math.random() * 89 )+ 10 ; } } //output for (int[] is : arr) { for (int x : is) { System.out.print(x+" "); } System.out.println(); } }
Class and object of the fifth lesson
Course objectives
1. Understand classes and objects
2. Create classes and objects - properties and methods
3. Construction method
4. Overloading of methods
####5. [difficulty] static method / final termination method
1, Class loading mechanism and memory model
The virtual machine loads the data describing the Class from the Class file into the memory, verifies, converts, parses and initializes the data, and finally forms a java type that can be directly used by the virtual machine, which is the Class loading mechanism of the virtual machine.
(1) Class life cycle
- Loading
- Verification
- Preparation
- Resolution
- Initialization
- Using
- Unloading
(2) Class loading process
The loading process of class includes loading, verification, preparation, parsing and initialization
Class loading is mainly divided into the following three steps:
1. Load: find the corresponding according to the path class file
This step will use the class loader.
Loading is a stage of class loading. Be careful not to confuse it.
The loading process completes the following three things:
-
Get the binary byte stream defining the class through the fully qualified name of the class.
-
Convert the static storage structure represented by the byte stream into the runtime storage structure of the method area.
-
A Class object representing this Class is generated in memory as an access to various data of this Class in the method area.
2. Connection:
- Verify: check the correctness of the class to be loaded;
- Preparation: allocate space for the static variable of the class. At this time, the static variable is still zero (not yet in the initialization stage) / / when declared in the class
static will create a memory store - Resolve: convert symbolic reference of constant pool to direct reference
-
Symbol reference:
Symbol reference uses a group of symbols to describe the referenced target. The symbol can be any form of literal quantity, as long as it can be located to the target without ambiguity. The symbol reference has nothing to do with the memory layout implemented by the virtual machine, and the target of the reference may not have been loaded into memory. -
Direct reference:
A direct reference can be a pointer directly to the target, a relative offset, or a handle that can be located indirectly to the target. Direct reference is related to the memory layout implemented by the virtual machine. Half of the direct references translated by the same symbol reference on different virtual machine instances will not be the same. If there is a direct reference, the reference target must already exist in memory.**Note: the instance variable will not allocate memory at this stage. It will be allocated in the heap with the object when the object is instantiated. It should be noted that instantiation is not a process of class loading. Class loading occurs before all instantiation operations, and class loading is only carried out once, and instantiation can be carried out multiple times.
3. Initialization: initialize static variables and static code blocks
The initialization phase really starts to execute the Java program code defined in the class. The initialization phase is the stage when the virtual machine executes the class constructor () method
Cheng. In the preparation stage, the class variable has been assigned the initial value required by the system once, and in the initialization stage, it is determined by the programmer through the program
Subjective plan to initialize class variables and other resources.
summary
In Java, the class loader loads a class into the Java virtual machine through three steps: loading, connecting and initialization. The link can be divided into three steps: verification, preparation and parsing. In addition to parsing, other steps are completed in strict order. The main work of each step is as follows:
- Loading: find and import binary data of classes or interfaces;
- Link: perform the following verification, preparation and analysis steps, in which the analysis steps are optional;
- Check: check the correctness of the binary data of the imported class or interface;
- Preparation: allocate and initialize the storage space for the static variables of the class;
- Resolve: convert symbolic references to direct references
- Initialization: the initialization Java code and static Java code block of the static variable of the activation class
2, Class initialization timing
- Create an instance of the class. new, reflection, deserialization
- Class method using a class – static method
- Accessing class variables of a class or assigning class variables
- Reflect the class object that creates a class or interface. Class.forName(“Hello”);— Note: loadClass call
ClassLoader.loadClass(name,false) method, no link, naturally no initialize - Initialize subclasses of a class
- Directly use Java Exe to run a main class. That is, cmd java program will initialize this class first.
Class loader
Although the class loader is only used to load classes, it also plays a role in judging whether the two classes are the same.
For any class, the class loader that loads it and the class itself need to establish its uniqueness in the java virtual machine.
A java program consists of several class file. When the program is running, it will call an entry function of the program to call the phase of the system
Off functions, which are encapsulated in different class files.
- When the program is started, it will not load all the class files used by the program at one time, but dynamically load a class file through java's class loading mechanism according to the needs of the program Class files are stored in memory, so that class files can be referenced by other classes only after they are loaded into memory. Therefore, the class loader is used to dynamically load class files into memory.
How does the class loader determine that it is the same class
- A class in java is identified by a fully qualified class name - package name + class name
- A class in the jvm is identified by its fully qualified class name + loader - package name + class name + loader name
Type of class loader
1. From the perspective of virtual machine:-
- One is to start the class loader (Bootstrap ClassLoader), which is implemented in C + + language (in HotSpot virtual machine) and is a part of the virtual machine itself;
- The other is all other class loaders. These class loaders are implemented in Java language, independent of the virtual machine, and all inherit from Java lang.ClassLoader.
1. From the perspective of developers:
- Bootstrap class loader: responsible for loading java_ The class library under home / lib is loaded into memory (such as rt.jar). Since the boot class loader involves the local implementation details of the virtual machine, the developer cannot directly obtain the reference of the boot class loader, so = = direct operation through reference is not allowed== Loading java core classes
- Extension class loader: it is responsible for Java_Home /lib/ext or by the system variable Java The class library in the location specified by ext.dir is loaded into memory. Developers can use the standard extension class loader directly.
- Application class loader: by Sun
AppClassLoader (sun.misc.Launcher$AppClassLoader). Because this class loader is
The return value of getSystemClassLoader() method in ClassLoader, so it is generally called system class loader. It is responsible for loading the class library specified in the user CLASSPATH. Developers can use the system class loader directly. Default use
Static methods can only access static methods and properties; Non static methods can access static and non static methods and properties
Question 1: how to initialize and assign static attribute?
Use static constructor
static{ }
Question 2: what is a code block in JAVA? What code blocks are there?
//The code in braces in java is called a code block
{ }
Reference website: https://blog.csdn.net/qq_36906073/article/details/
There are three categories:
- Common code block: class name {} function name {}
- Construction code block: {} execute before constructor
- Static construction code block static {}
Execution order: static construction code block -- > construction code block -- > constructor
Question 3: why do you need to construct code blocks when you have a construction method?
Because the constructor can be overloaded. Therefore, put the same code of all construction methods (the same initialization work) into the construction code block to reuse the code!
Knowledge points: static class attributes and class methods
Class names are always used xxx
The sixth class
1, Access modifier
public private protect nothing (friendly)
- For class, only public and friendly (package permissions – different packages cannot be accessed)
- Access modifiers modify properties and methods
-
private can only be accessed in a class
-
public is accessible anywhere
-
protected A. It must be in the inheritance relationship. B. The child class inherits the protected variable of the parent class, which is not limited by the package
-
There is no package permission. You can only access in the same package, even if the variable is an inheritance relationship.
-
The final modifier variable indicates that the variable is a constant
-
The final modifier indicates that the method cannot inherit
-
The final modifier class indicates that the class has no subclasses
-
-
static modifier
Course objectives - inheritance
-
The subclass inherits the parent class?
-
Parent class - abstract class
-
Parent class - terminal class
-
Godfather - Interface
public protected (default ) private
1. The subclass inherits the methods and properties of the parent class
Memory model obj=new Child()
2. Do access rights affect inheritance
A . When the attribute in the parent class has access to the attribute of the subclass of the permission modifier.
B. If a property or method in the parent class is protected
/** This is a document annotation through Javadoc Exe to export help documents html */ class A { int x; //default friendly public String print(){} } /** This is a subclass of class A, which is used to extend xxx and override the print method */ class B extends A{ private int x; public B(){stu=new Student();} public int getXOfA(){ this.x= 12 ; return super.x; } /*function*/ public String print(int y){ int y=y; } } class test{ static void main(){ B objA=new B(); objA.print(); } }
c. Inheritance does not change access rights – access rights remain the same
rewrite
In addition to inheriting the properties and methods of the parent class.
A. The subclass and the parent class have the same attribute name and method. The same here means exactly the same
B. The properties are the same – the properties of the parent class are hidden. Display calling parent class attribute super this
C. Same method -- override
D. The method access permission of subclass override cannot be lower than that of parent method
E. static method and constructor cannot be overridden
A.print() super.print(); What is the difference between?
The root parent class of all classes in JAVA is called Object
heavy load
It refers to that there are multiple methods with the same method name in the same class, and the parameters must be different (number and type)
static methods can be overloaded
Construction methods can be overloaded
3. When creating subclass objects, the call order of subclass and parent constructor
If the parent class does not have a parameter constructor, the default first sentence super() in the subclass constructor calls the parent class parameterless constructor.
If the parent class has a parameter constructor, the subclass must display and call super(xx, xxx)
Inner class and anonymous class
I Course objectives
1. Understand the meaning and significance of internal classes.
2. Master anonymous classes
II Inner class
Think 1: what elements (members) are there in a class?
class A{ private int x;//Member variables (properties) public void getX(){//Member function (method) return x; } private class B{ //Internal class member * new! } }
Thinking 2: what is the meaning of existence?
interface Cont{ void getName(); } class A{ private int x;//Member variables (properties) public void getX(){//Member function (method) return x; } private class B implementes Cont{ //Inner class member * new!} public void getName(){System.out.println("Class B!");} } public Cont GetObj(){ Cont b1=new B(); //Interface callback return b1; } } class Test{ main(){ A a=new A(); Cont obj= a.GetObj(); obj.getName(); } }
- The first advantage of using inner classes: if the inner class is private, it cannot be accessed by other classes. But it can be accessed through interfaces or abstract classes. In this way, the inner class implements the encapsulation idea.
- The second advantage of inner class: an inner class object can access the content of the external class object that created it, even including private variables!
3, Anonymous class
interface Cont{ void getName(); } class A{ private int x;//Member variables (properties) public void getX(){//Member function (method) return x; } public Cont GetObj(){ //reference method //Combine the definition of the class and the instantiation of the new object object into one return new Cont(){ public void getName(){System.out.println("Class B!");} }; //Interface callback } } class Test{ main(){ A a=new A(); Cont obj= a.GetObj(); obj.getName(); } }
polymorphic
##1, Course objectives
-
Understand why polymorphism is needed: solve the problem of code scalability.
-
Understand and master the knowledge of polymorphism
-
Overload override
-
Upper transformation object and lower transformation object
-
Interface call
-
Abstract class, interface
2, Why polymorphism is needed? The benefits of polymorphism
Class exercise: implement the following classes with code and write a test class for test output
[the transfer of external chain pictures fails. The source station may have anti-theft chain mechanism. It is recommended to save the pictures and upload them directly (img-n76lxbQ6-1624097593989)(E:\Typora_Copy_Image23835087278.png)]
class Animal{ public void getVoice(){System.out.println("Animal voice!");} } class Dog extends Animal { public void getVoice(){System.out.println("Woof, woof!");} } class Cat extends Animal { public void getVoice(){System.out.println("Meow!");} } class Tiger extends Animal { public void getVoice(){System.out.println("Ouch!");} } public class MainClass { public static void main(String args[]) { Cat c1=new Cat(); Dog d1=new Dog(); Tiger t1=new Tiger(); tune(c1); tune(d1); tune(t1); } public static void tune(Dog i) { i.getVoice(); } public static void tune(Cat i) { i.getVoice(); } public static void tune(Tiger i) { i.getVoice(); } }
Think about what code needs to be added when adding an animal (Brid)?
-
Do not change the original code.
-
The less code you add, the better.
3, Upper transformation object
Cat c=new Cat();//Parent + child methods and properties Animal a=new Cat();//Parent class methods and properties (inheritance) + overridden methods, hidden properties
What methods and properties does a object have? Why?
Only methods and properties inherited by the parent class + hidden properties and overridden methods can be accessed
Deep thinking:
1. What are the functions of the methods and attributes of the parent class standard
2. Is it meaningful to implement the method of the parent class?
###4, Lower transformation object
Cat c=new Cat();//Parent + child methods and properties Animal a=new Cat();//Parent class methods and properties (inheritance) + overridden methods, hidden properties //Convert object a down to its subclass Cat object c=(Cat)a;
The next transformation object must
- Cast type
- (important) object a can be converted to the Cat type of Object c because object a is actually created as new cat(), so the type of strong conversion must be
It must match the type actually created
###5, Abstract classes and abstract methods
####1. Abstract method
- No way to implement
- With abstract modification
abstract public void getVoice() ;
####2. abstract class
- Class with abstract modifier
- If the class has abstract methods, the class must be abstract
- An abstract class cannot new a concrete object.
abstract class Animal {}
###6, Interface
-
Why interfaces exist: JAVA does not support multi inheritance in order to give special specifications (rules)
-
What is the difference between a (Abstract) parent class and an interface? How-- Design mode
A. Attributes can only be constants; B. Methods are all abstract methods by default (i.e. no implementation) - only focus on operations, not implementation details.
There are only constants and abstract methods in the interface -
Learn how to define and use interfaces
- Meaning of interface – interface callback
class A implements Printable{ public void add(){System.out.println("A");} } class B implements Printable{ public void add(){System.out.println("A");} } class Test{ public static void main(String[] args) { add(new A()); add(new B()); } public static void add(Pr p){ //Interface callback p.add(); } }
Summary: polymorphic implementation method; Method overloading, method rewriting, upper transformation object, interface callback
- How to use interfaces
interface Printable{ final int max= 20 ;//Can only be constant public void add();// Common abstract method (default) //===========New features of java8 (understand)============================= //New features in Java 8 allow default methods default void print(){System.out.println("Default method");} //Static methods and default methods of java 8 features static void haha(){ System.out.println("java8 Characteristic static method"); } //New java 8 feature: support for private methods private void java9(){} }
-
The comparison between interface and abstract class is as follows:
1)abstract classes and interfaces can have abstract methods
- The interface can only have constants, not variables; The abstract class can have either constants or variables.
3) There can also be non abstract methods in the abstract class, but not the interface.
Generics and collections
1, Course objectives
2, Generics
###1. generic method
public class MyClass { public <T> void print(T[] x) { //Generic method, which passes the data type into T as a variable for (T ele : x) { System.out.println(ele); } } } class TestClass{ //Test class public static void main(String[] args) { Integer x[]={ 1 , 2 , 34 , 5 }; Double y[]={2.1,3.2,445.23,4.23}; Character ch[]={'a','b','c','d','e'}; Short sh[]={ 1 , 2 , 3 , 4 }; new MyClass().print(sh); } }
Generic: the data type (uncertain) is passed into the method as a variable, so T is a data type variable because there is a description in T above
be careful:
- Generic data type parameters can only be class types (or reference data types), not native data types - basic data types.
- Type inference: generic methods can infer the data type through the passed in parameters (that is, determine the data type of T through parameters)
Question: why do I have to use class types?
###2. Generic class
public class MyClass<T> { //Defines a generic class -- when declaring a class, it declares a data type variable T public void print(T[] x) { for (T ele : x) { System.out.println(ele); } } public void getId(T[] zz,int id){ } } class TestClass{ //Test class public static void main(String[] args) { Integer x[]={ 1 , 2 , 34 , 5 }; Double y[]={2.1,3.2,445.23,4.23}; Character ch[]={'a','b','c','d','e'}; Short sh[]={ 1 , 2 , 3 , 4 }; MyClass<Object> myclass=new MyClass<Object>(); //When creating an object, specify the data type myclass.print(sh); } }
be careful:
- For generic classes, the scope of type parameter T is members in all classes.
- MyClass myclass=new MyClass(); `` Class name + < data type > corresponding class name
If no specific < data type > is given when creating an object, the compiler adds one by default - When creating an object, the given class name < data type T > t is the upper bound of the parameter data type, that is, the subsequent variable type must be type T or a subclass of type T
3. Generic interface
public interface MyInt<T> { //Defines a rule, public int bj(T y); } //Define two classes that implement the MyInt interface. These two classes must have bj this method public class Student implements MyInt<Student> { private String name; private int age; public Student(String name, int age) { this.name = name; this.age = age; } @Override public int bj( Student y) { return this.age - y.age; } } class Animal implements MyInt { private String name; private double money; public Animal(String name, double money) { this.name = name; this.money = money; } @Override public int bj( Object y) { return (int) (this.money-((Animal)y).money); } } //In the use of generic classes, the upper bound of parameters is specified (i.e. the passed in parameters A1 and A2). Their type must be Myint, which implements the interface Object of public class MyClass<T extends MyInt> { public int Max(T a1,T a2){ return a1.bj(a2); //Only method = = one regulation in MyInt can be used }
be careful:
-
Generic interface, which specifies a specification, is often used in combination with "upper bound"
-
Understand what is the "upper bound" of generic parameters; why use the "upper bound"“
3, Classroom practice
New circle class Circle , triangle Triangle They all belong to geometry Geometry Subclass of class, 1. Their related properties and methods are given respectively getArea() Find area 2. Define a test class A,Define two arrays cArray;tArray Store separately Circle and Triangle Class (at least 5 for any given) B,Using generic knowledge, define a sort generic method to sort the incoming array, Basis: area. Bubble sorting Note: each class implements a collation
Realization idea:
1. Define an abstract class Geometry and define the abstract method getarea(); Max (Geometry GEO) / / compare the size of two geometries
public abstract class Geometry { abstract public double C(); abstract public boolean Max(Geometry c); }
- Define two subclasses to inherit Geometry and implement abstract methods; Pay attention to understand the transformation object on the parameters of Max method
public class Circle extends Geometry { private int r; public Circle(int r) { this.r = r; } @Override public double getArea() {//Override the parent class method (implement the abstract method) to find the area return Math.PI * r * r; } @Override public boolean Max(Geometry c) {//Override the parent class method (implement the abstract method) to compare the size with the passed in object return (this.getArea() > c.getArea()); } @Override public String toString() {//Output -- overwrite return "Circle{" + "r=" + r + '}'; } } //Define the triangle class, define relevant attributes, and implement the getArea method to calculate the area and compare the maximum value public class Triangle extends Geometry { private int bottom;//Bottom length private int height;//high public Triangle(int bottom, int height) { this.bottom = bottom; this.height = height; } @Override public double getArea() {//Override the parent class method (implement the abstract method) to find the area return 0.5bottomheight; } @Override public boolean Max(Geometry c) {//Override the parent class method (implement the abstract method) to compare the size with the passed in object return this.getArea()>c.getArea(); } @Override public String toString() {//Output -- overwrite return "Triangle{" + "bottom=" + bottom + ", height=" + height + "} Area"+this.getArea(); } }
- Define test class TestClass implementation array
public class TestClass { /** @param args the command line arguments 2. Define a test class A and two arrays cArray;tArray Store the objects of Circle and Triangle classes respectively (at least 5 at any given time). B. use generic knowledge to define a sort The generic method sorts the incoming array according to the area. Bubble sorting */ public static void main(String[] args) { //--------------Create an array and assign values-------------- Circle cArray[] = new Circle[ 5 ]; for (int i = 0 ; i < cArray.length; i++) { cArray[i] = new Circle((int) (Math.random() * 10 ) + 10 ); } Triangle tArray[] = {new Triangle( 12 , 9 ), new Triangle( 14 , 8 ), new Triangle( 10 , 12 ), new Triangle( 15 , 7 ), new Triangle( 10 , 10 )}; System.out.println("==Output before sorting=="); print(cArray); print(tArray); System.out.println("==Output after sorting=="); Sort(cArray); print(cArray); Sort(tArray); print(tArray); //Bubble sort -- generic method pay attention to the use of upper bound public static <T extends Geometry> void Sort(T[] myArr) { for (int i = 0 ; i < myArr.length; i++) { T tA = myArr[i]; for (int j = i + 1 ; j < myArr.length; j++) { T tB = myArr[j]; if (tA.Max(tB)) { T tmp = tA; myArr[i] = tB; myArr[j] = tmp; } } } } //Define an output method using polymorphism public static void print(Geometry[] geoArry) { for (Geometry circle : geoArry) { System.out.println(circle); } } //Define an output method using generics public static <T>void print(T[] geoArry) { for (T ele : geoArry) { System.out.println(ele); } } }
4, Set class
//sort //A uses the algorithm class Collections to either adopt the default collation or specify the temporary collation Collections.shor //B only temporary sorting rules can be specified by using the sorting method of collection class // Collections.sort(myLst, new Comparator<Student>() { // @Override // public int compare(Student o1, Student o2) { // return (int) (o1.getScore() - o2.getScore()); // } // }); myLst.sort(new Comparator<Student>() { @Override public int compare(Student o1, Student o2) { return (int) (o2.getScore() - o1.getScore()); } }); Think: first, sort the grades from big to small, and sort the same grades from small to big according to age
thread
What is a thread
Program = algorithm + data structure
The program runs at least one process (. exe)
A process needs to run multiple tasks, which are completed by multiple threads. Threads are the smallest unit of a program. Is assigned to different CPU cores to run.
###How
Two methods
A. Adopt the method of inheriting Thread class.
B. The method of implementing Runnable interface is adopted.
Specific code
1, Methods of subclasses of Thread class
class MyThread extends Thread{ //Must be a subclass of Thread class @Override public void run() { print(); // The code that needs multithreading operation is put into the rewritten run method } public void print() { while (true) { //System.out.println(x++); } } } class TestClass{ MyThread th=new MyThread(); th.start(); //Call the start method of the Thread parent class and assign the tasks in the run method to the CPU core }
2, Implement Runnable interface
class MyThIntel implements Runnable{ @Override public void run() { while(true){} // The code that needs multithreading operation is put into the rewritten run method } } class TestClass{ MyTh myth = new MyTh();//The class implementing the interface has no start method, so it needs to be wrapped with Thread class Thread th = new Thread(myth); th.start(); //Call the start method of the Thread class object and assign the task in the run method of the object myth to the CPU core function }
Summary:
Understand the run() method and start () method: run() – define the code for multithreading; start() - start the thread and allocate CPU resources
Thinking: why do we need to implement the Runnable interface with the multithreading method of Thread subclass?
1. Identify the current thread;
Give the name: thread object setName()
Get the name thread currentThread(). getName()
Class exercise: Tortoise and rabbit race
Requirements: 1. The rabbit runs 5 meters per second, but has to rest for 2 seconds every 10 meters; 2. Tortoise 4 meters per second, no rest; 3. Who reaches the finish line first, the game is over; 4. Runway length: 100M
class Race{ //runway length //Remaining distance run distance //Speed m/s //Rest interval 10- //Rest duration 2 }
Scheme I; Interface mode is adopted
package javaapplication1; import java.util.logging.Level; import java.util.logging.Logger; public class Race implements Runnable { private int speed;//How many meters per second? private int sleep;//How many seconds to rest? If not, it is - 1 rest interval private int sleepTime;//How many seconds and duration of each break private int len;//runway length //Construction method public Race(int speed, int sleep, int sleepTime, int len) { this.speed = speed; this.sleep = sleep; this.sleepTime = sleepTime; this.len = len; } @Override public void run() { int dis= 0 ;//Distance run (m) while (true) { len -= speed;//Total length dis += speed; if (len <= 0 ) { System.out.println("#====="+Thread.currentThread().getName()+ "Reach the end!========="); break; }//Using class method thread Currentthread() gets the currently running thread object. System.out.println(Thread.currentThread().getName()+"It's still far from the end Leftover"+len+"rice"); //Add rest if(sleep>- 1 && dis % sleep== 0 ){ System.out.println("#---"+ Thread.currentThread().getName() +" on Start sleeping!========="); Thread.sleep(sleepTime* 1000 ); } try { Thread.sleep( 1000 ); } catch (InterruptedException ex) { Logger.getLogger(Race.class.getName()).log(Level.SEVERE, null, ex); } } } } //Test class public class TestClass { public static void main(String[] args) { final int distance = 100 ; Race rabbit = new Race( 5 , 10 , 2 , distance); Thread thR = new Thread(rabbit); thR.setName("rabbit"); //Use setName to give the thread a name thR.start(); Race tortoise = new Race( 4 , - 1 , - 1 , distance); Thread thT = new Thread(tortoise); thT.setName("tortoise");//Use setName to give the thread a name thT.start(); } }
Add rest –
Thread knowledge (extracurricular supplement)
1. Deadlock
The rabbit needs a runway when using the printer
The tortoise waited for the rabbit to use the printer and occupy the runway
The root cause of Deadlock: monopoly of resources;
2. Asynchronous synchronization
Synchronization: multiple threads use the same method at the same time - the sharing of resources is synchronized and exclusive, that is, one thread accesses the method and other threads cannot access it.
3. Scheduling priority
Setpriority (int grade) the higher the grade value, the higher the priority
timer thread
Timer
1. Difference between process and thread
1.1 an exe runs as a process
1.2 a process is run by multiple threads, which is the smallest unit running in the computer
1.3 purpose of multithreaded programming: make full use of computer resources (computing resources)
1.4 multi thread programming will encounter resource contention (deadlock)
1.5 high salary for Java = = = = high concurrency
1.6 UI programming main process – > main thread
2.java multithreaded programming
2.1 Thread subclass of the first method
A. Define a subclass whose class is Thread
B. Right click to insert the override method run
C. Write the running code to the run method
D. Use setName and thread Currentthread() refers to getName of the current thread to get the name of the current thread
2.2 the second method implements the interface Runnable
Problem encountered: if it is not feasible to implement multithreading using inheritance method in UI?
JAVA can only have one parent class, but it can have multiple interfaces
A implementation of run method
When calling B, wrap it with Thread class to run the Thread with start() method
Large number class determinant
import java.math.BigDecimal; import java.math.BigInteger; /** * Use a large number of classes to achieve 1 + 1 / 1+ 1/2!+... + 1/n! * @author Administrator */ public class Compute { public static void js(int n) { //double sum = 0; BigDecimal sum = new BigDecimal("0"); for (int i = 0 ; i < n + 1 ; i++) { BigDecimal x = new BigDecimal("1"); BigDecimal y = x.divide(new BigDecimal(jc(i)), 20 , BigDecimal.ROUND_HALF_UP);//1/i! System.out.println("y: " + y); sum = sum.add(y); } System.out.println(sum.toString()); } public static BigInteger jc(int i) { if (i == 0 ) { return BigInteger.valueOf( 1 ); } //long res = 1; BigInteger res = new BigInteger("1"); for (int j = 1 ; j <= i; j++) { res = res.multiply(BigInteger.valueOf(j)); } System.out.println(i + "The factorial of is" + res.toString()); return res; } }