JAVA learning (middle)
2019 Silicon Valley Java introduction video tutorial, BiliBili link: https://www.bilibili.com/video/BV1Kb411W75N?p=5
4, Object oriented (I)
The object-oriented feature is the core and play of Java learning.
4-1 process oriented and object-oriented
l Object Oriented Programming
l process oriented programming
Both are ideas, and object-oriented is relative to process oriented. Process oriented, which emphasizes the functional behavior. Taking the function as the minimum unit, consider how to do it. Object oriented, encapsulating functions into objects, emphasizing the objects with functions, taking class / object as the minimum unit, and considering who will do it.
Object oriented puts more emphasis on the application of the thinking methods and principles adopted by human beings in daily thinking logic, such as abstraction, classification, inheritance, aggregation, polymorphism, etc.
l three characteristics of object-oriented
Encapsulation
Inheritance
Ø polymorphism
Overview of object-oriented thinking
l programmers have transformed from process oriented executors to object-oriented commanders
l ideas and steps of analyzing problems with object-oriented analysis method:
Ø select the real-world entity targeted by the problem according to the needs of the problem.
Ø find the attributes and functions related to solving problems from entities, and these attributes and functions form classes in the conceptual world.
Ø abstract entities are described in computer language to form the definition of classes in the computer world. That is, with the help of a certain program language, the class is constructed into a data structure that can be recognized and processed by the computer.
Instantiate a class into an object in the computer world. Object is the ultimate tool to solve problems in the computer world.
Three main lines of object-oriented programming
1) Class and composition of class: internal class of attribute method constructor code block
2) Characteristics of object-oriented programming: encapsulation, inheritance, polymorphism (abstraction)
3) Other keywords: this super package import static final abstract interface
4-2 basic elements of Java language: classes and objects
Class
Class and object are the core concepts of object-oriented.
Class is a description of a class of things, which is an abstract and conceptual definition
Ø an object is each individual of such things that actually exist, so it is also called an instance. "Everything is an object"
Components of class
1) attribute (member variable, Field)
2) Method (member Method, function, Method)
The variables declared by the class are called objects, that is, the class is the template used to create objects. Class implementation includes two parts: class declaration and class body
Syntax format of class
Modifier class Class name { Attribute declaration; Method declaration; } Description: modifier public: Class can be accessed arbitrarily. The body of the class needs to be{}Enclose, for example: public class Person{ private int age ; //Declare private variable age public void showAge(int i) { //Declare method showAge() age = i; } }
Precautions for class naming
Here, Something Class file name OtherThing.java class Something { private static void main(String[] something_to_do) { System.out.println("Do something ..."); } } answer: correct. No one ever said Java of class The name must be the same as its file name. but public class Your name must be the same as the file name.
Description of the relationship between classes
1. Dependency
2. Related relationship
3. Polymerization
4. Combination
5. Succession
Generalization, also known as generalization, is-a relationship
4-3 creation and use of objects
Instantiation of a java class, that is, creating an object of the class
An object is each individual of such things that actually exist, so it is also called an instance. "Everything is an object"
Ø create object syntax: class name object name = new class name ();
Ø use object name Object members (including properties and methods)
Anonymous object
l we can also call the method of the object directly without defining the handle of the object. Such objects are called anonymous objects.
Ø e.g.: new person() shout();
l usage
Ø if you only need to make one method call to an object, you can use anonymous objects.
Ø we often pass anonymous objects as arguments to a method call.
One of the members of class 4-4: attribute (field)
Default initialization assignment of object properties
When an object is created, various types of member variables will be initialized and assigned automatically. All variable types except the basic data type are reference types
Member 2 of class 4-5: method
What is a method (method, function):
Ø a method is an abstraction of the behavior characteristics of a class or object, which is used to complete a function operation. Also called a function or procedure in some languages.
Ø the purpose of encapsulating functions into methods is to realize code reuse and simplify code
Ø methods in Java cannot exist independently. All methods must be defined in classes. Provide the realization of some function
Return value type:
Ø no return value: void.
If there is a return value, declare the type of the return value. Use with the return value in the method body
Method name: it belongs to an identifier. When naming, follow the identifier naming rules and specifications, "see the meaning of the name"
Formal parameter list: can contain zero, one or more parameters. When there are multiple parameters, the middle is separated by
Return value: the data returned by the method to the program calling it after execution.
//The data type returned by a method can be one of any data types in Java. When a method does not need to return data, the return type must be void. int speak(){ //Parameterless method header return 23; } int add(int x,int y,int z) { //Method header with parameters return x+y+z; } //Methods in classes can also be divided into instance methods and class methods When a method is declared, the instance method without the keyword static in front of the method type and the class method with the keyword static. public class Person{ private int age; public int getAge() { return age; } //Declare method getAge public void setAge(int i) { //Declare method setAge age = i; //Assign the value of parameter i to the member variable age of the class } }
Method call
l method is called by method name, and only the called method will execute.
l process analysis of method call:
be careful
Ø about return value type:
void: indicates that this method does not need to return a value
Method with return value: there must be a variable corresponding to return + return value type at the end of the method
Note: void and return cannot appear in one method at the same time. Like a pair of "friends".
Ø other methods or properties of this class can be called in the method, but the method cannot be defined in the method!
Ø if there is no specific return value and the return value type is represented by the keyword void, the return statement may not be used in the method body. If used, it is only used to end the method.
Ø when defining a method, the result of the method should be returned to the caller for processing.
Ø only methods or attributes can be called in methods, and methods cannot be defined inside methods.
4-6 further discussion on Methods
1. Method overloaded
Concept of overloading |
---|
In the same class, more than one method with the same name is allowed, as long as their parameter number or parameter type are different. |
Characteristics of heavy load: |
It has nothing to do with the return value type. It only depends on the parameter list, and the parameter list must be different. (number of parameters or parameter type). When calling, it can be distinguished according to different method parameter lists. |
Overload example: |
//Returns the sum of two integers int add(int x,int y){return x+y;} |
//Returns the sum of three integers int add(int x,int y,int z){return x+y+z;} |
//Return the sum of two decimals double add(double x,double y){return x+y;} |
Requirements: 1 In the same class (methods defined in the same type)
2. Method names must be the same
3. Different parameter lists of methods (① different number of parameters ② different parameter types)
Supplement: method overloading has nothing to do with the return value type of the method!
The return type of the method and the name of the parameter are not involved in the comparison
Method overloading is a manifestation of polymorphism.
The Overloaded method can change the type of return value
//Defines the sum of two int variables public int getSum(int i,int j){ return i + j; } //Defines the sum of three int variables public int getSum(int i,int j,int k){ return i + j + k; } public void method1(int i,String str){ } public void method1(String str1,int j){ } Using overload method can bring convenience to programming. For example, System.out.println()Method is a typical overloaded method. Its internal declaration form is as follows: public void println(byte x) public void println(short x) public void println(int x) public void println(long x) public void println(float x)
2. Method of variable parameter
The * * Varargs(variable number of arguments) * * mechanism is provided in Java se 5.0, which allows you to directly define formal parameters that can match multiple arguments. Thus, you can pass a variable number of arguments in a simpler way.
//Before JDK 5.0: array parameters are used to define methods, and multiple variables of the same type are passed in public static void test(int a ,String[] books); //JDK5.0: variable number formal parameters are used to define methods, and multiple variables of the same type are passed in public static void test(int a ,String...books);
explain:
\1. Declaration format: method name (parameter type name... Parameter name)
\2. Variable parameters: the number of parameters of the type specified in the method parameters section is variable. Multiple: 0, 1 or more
\3. Methods with variable number of formal parameters and methods with the same name constitute overloads with each other
\4. The use of variable parameter method is consistent with the use of array in method parameter part
\5. The parameter part of the method has deformable parameters, which need to be placed at the end of the formal parameter declaration
\6. At most one variable number parameter can be declared at the parameter position of a method
3. Value transfer mechanism of method parameters
l method, which must be called by its class or object. If the method contains parameters:
Ø formal parameter: parameter in method declaration (parameter in method parentheses in method declaration)
Ø actual parameter: the parameter value actually passed to the formal parameter when the method is called (the value of the parameter actually passed in when the method is called)
L how can Java's argument values be passed into the method?
There is only one way to pass values in Java. That is, a copy (Replica) of the actual parameter value is passed into the method, and the parameter itself is not affected.
Ø formal parameter is a basic data type: pass the "data value" of the basic data type variable of the argument to the formal parameter (pass the value of the argument to the variable of the basic data type of the formal parameter)
Ø formal parameter is a reference data type: pass the "address value" of the reference data type variable of the argument to the formal parameter (pass the value of the reference type variable of the argument (the first address value of the object entity in the corresponding heap space) to the reference type variable of the formal parameter.)
[typical example 1]
public static void main(String[] args) { TestArgsTransfer tt = new TestArgsTransfer(); int i = 10; int j = 5; System.out.println("i:" + i + " j:" + j);//i : 10 j : 5 // Exchange the values of variables i and j // int temp = i; // i = j; // j = temp; tt.swap(i, j);//Pass the value of i to m and the value of j to n System.out.println("i:" + i + " j:" + j);//i : 10 j : 5 } //Define a method to exchange the values of two variables public void swap(int m,int n){ int temp = m; m = n; n = temp; System.out.println("m:" + m + " n:" + n); }
[typical example 2]
public class TestArgsTransfer1 { public static void main(String[] args) { TestArgsTransfer1 tt = new TestArgsTransfer1(); DataSwap ds = new DataSwap(); System.out.println("ds.i:" + ds.i + " ds.j:" + ds.j); tt.swap(ds); System.out.println(ds); System.out.println("ds.i:" + ds.i + " ds.j:" + ds.j); } //Exchange values of elements public void swap(DataSwap d){ int temp = d.i; d.i = d.j; d.j = temp; System.out.println(d);//Print the value of the reference variable d } } class DataSwap{ int i = 10; int j = 5; }
[typical example 3]
//The value passed by the parameter cannot be higher than the level of the parameter. class Circle { double rad; Circle(double r) { rad=r; } void changeRad(double newRad) { rad=newRad; } } class Test { public static void main(String args[]) { Circle cir=new Circle(10); cir.changeRad(100);//100 (int) cannot be higher than double } }
Method parameter transfer mechanism
4. Recursive method
Recursive method: a method body calls itself.
l method recursion contains an implicit loop, which will repeatedly execute a piece of code, but this repeated execution does not need loop control.
l recursion must recurse in the known direction, otherwise this recursion will become infinite recursion, similar to dead loop.
//Calculate the sum of all natural numbers between 1-100 public int sum(int num){ if(num == 1){ return 1; }else{ return num + sum(num - 1); } }
4-7 one of the object-oriented features: encapsulation and hiding
Encapsulation is to surround the process and data, and the access to the data can only be through the defined interface. Object oriented computing begins with the basic concept that the real world can be depicted as a series of fully autonomous and encapsulated objects that access other objects through a protected interface.
l why package? What is the function and meaning of encapsulation?
Ø if I want to use the washing machine, I just need to press the switch and washing mode. Is it necessary to understand the internal structure of the washing machine? Is it necessary to touch the motor?
l our programming pursues "high cohesion and low coupling".
High cohesion: the internal data operation details of the class are completed by themselves, and external interference is not allowed;
Ø low coupling: only a small amount of methods exposed to the outside are used.
l hide the internal complexity of objects and only expose simple interfaces. It is convenient for external calls, so as to improve the scalability and maintainability of the system. Generally speaking, hide what should be hidden and expose what should be exposed. This is the design idea of encapsulation.
L in Java, the data is declared as private, and then public methods are provided: getXxx() and setXxx() to realize the operation of this attribute, so as to achieve the following purposes:
Hide the implementation details of a class that do not need to be provided externally;
Ø users can only access data through pre-defined methods, and can easily add control logic to limit unreasonable operations on attributes;
Ø easy to modify and enhance the maintainability of the code;
The idea of encapsulation: ① privatize the properties of the class, ② provide public methods (setter & getter) to realize the call.
public class Animal{ private int legs;//The attribute legs is defined as private and can only be accessed internally by the Animal class public void setLegs(int i){ if (i != 0 && i != 2 && i != 4){ System.out.println("Wrong number of legs!"); return; } legs=i; } public int getLegs(){ return legs; } } public class Zoo{ public static void main(String args[]){ Animal xb=new Animal(); xb.setLegs(4); //xb.setLegs(-1000); // xb.legs = -1000; // illegal System.out.println(xb.getLegs()); } }
Four permission modifiers
1. The permissions from large to small are: public protected (default) private
2. All four permissions can be used to modify attributes, methods and constructors
The third member of Class 4-8: constructor (or construction method)
Constructor is a special method. Its name must be exactly the same as the name of its class, and there is no type.
The constructor is used when creating objects. It is mainly used to initialize each member variable, so as to give a reasonable initial state to the object created by the class.
Characteristics of constructors
Ø it has the same name as the class
Ø it does not declare the return value type. (different from declaring void)
Ø cannot be modified by static, final, synchronized, abstract, native, and cannot have a return statement return value
Function of constructor
Create objects; Initialize object
Ø for example: Order o = new Order(); Person p = new Person(“Peter”,15);
Ø just as we stipulate that every "person" must take a bath as soon as he is born, we can add the program code to complete the "bath" to the "person" constructor, so every "person" will automatically complete the "bath" as soon as he is born, and the program does not have to tell them to "take a bath" one by one when everyone is just born.
Syntax format
According to different parameters, constructors can be divided into the following two categories:
Ø implicit parameterless constructor (provided by default)
Ø explicitly define one or more constructors (no parameters, with parameters)
be careful:
Ø in the Java language, each class has at least one constructor
Ø the modifier of the default constructor is consistent with the modifier of its class
Ø once a constructor is explicitly defined, the system no longer provides a default constructor
Ø a class can create multiple overloaded constructors
The constructor of a parent class cannot be inherited by a child class
Constructor cannot be inherited, so Override cannot be overridden, but it can be overloaded and overloaded
- 1. When designing a class, if the constructor of the class is not explicitly declared, the program will provide an empty parameter constructor by default
- 2. Once the class constructor is explicitly defined, the default constructor is no longer provided.
- 3. How to declare the constructor of a class. Format: permission modifier class name (formal parameter) {}
- 4. Multiple constructors of a class constitute overloads
Sequence of attribute assignment of class object: ① default initialization of attribute
② explicit initialization of attributes
③ initialize the attribute through the constructor
④ passing object Method
Constructor Overload
1. Constructors are generally used to initialize objects while creating objects.
class Person{ String name; int age; public Person(String n , int a){ name=n; age=a;} }
2. Constructor overloading makes the creation of objects more flexible and convenient to create various objects.
//Constructor overload example: public class Person{ public Person(String name, int age, Date d) {this(name,age);...} public Person(String name, int age) {...} public Person(String name, Date d) {...} public Person(){...} }
3. The constructor is overloaded, and the parameter list must be different
public class Person { private String name; private int age; private Date birthDate; public Person(String name, int age, Date d) { this.name = name; this.age = age; this.birthDate = d; } public Person(String n, int a) { //When the shape participating member variable has different names, this can be omitted. If the same name must be added with this, it means calling the member variable name = n; age = a; } public Person(String n, Date d) { name = n; birthDate = d; } public Person(String n) { name = n; age = 30; } }
In addition to construction methods, other methods are divided into instance methods and class methods.
Example method:
That is, you can operate instance variables or class variables. When an object calls an instance method, the member variables in the method refer to the member variables assigned to the object,
The instance variables are different from those of other objects, that is, they occupy different memory space; Class variables are the same as other objects, that is, they occupy the same memory space.
Class method:
Only class variables can be operated. When an object calls a class method, the member variables in the method must be class variables, that is, the object and all objects share class variables.
Note: objects accessing their own variables and calling methods are restricted by access permissions.
Expand knowledge: JavaBean
l JavaBean is a reusable component written in Java language.
l the so-called javaBean refers to Java classes that meet the following standards:
Class is public
There is a public constructor without parameters
Ø has attributes and corresponding get and set methods
l users can use JavaBeans to package functions, processing, values, database access and any other objects that can be created with Java code, and other developers can use these objects through internal JSP pages, servlets, other JavaBeans, applet programs or applications. Users can think that JavaBeans provide a function of copying and pasting anytime, anywhere, without caring about any changes.
JavaBean example
public class TestJavaBean{ private String name; //Property is generally defined as private private int age; public TestJavaBean(){} public int getAge(){ return age; } public void setAge(int age){ this.age = age; } public String getName(){ return name; } public void setName(String name){ this.name = name; }
Expanding knowledge: UML class diagram
4-9 keyword: use of this
What is this?
l in Java, this keyword is difficult to understand, and its function is very close to its meaning.
Ø it is used inside the method, that is, the reference of the object to which the method belongs;
Ø it is used inside the constructor to represent the object that the constructor is initializing.
l this can call the properties, methods and constructors of the class
When to use this keyword?
Ø use this when the object calling the method needs to be used in the method. Specifically: we can use this to distinguish between attributes and local variables (call member variables through this). For example: this name = name;
1. Use this to call properties and methods
2. Use this to call the constructor of this class
be careful
Ø you can call other constructors overloaded in this class by using this (formal parameter list) in the constructor of this class!
Ø clear: the constructor cannot call its own constructor through this (formal parameter list)
Ø if n constructors are declared in a class, this (formal parameter list) is used in up to n - 1 constructors
Ø this (formal parameter list) must be declared on the first line of the constructor of the class! Use this() must be placed on the first line of the constructor!
Ø at most one this (formal parameter list) can be declared in a constructor of a class
Ø used in classes, it can be used to modify properties, methods and constructors
Ø indicates the current object or the object currently being created
Ø when the shape participating member variable has the same name, if the member variable needs to be used inside the method, this must be added to indicate that the variable is a class member
Ø in any method, if you use the member variable or member method of the current class, you can add this in front of it to enhance the readability of the program
Ø use this (formal parameter list) in the constructor to explicitly call other constructors overloaded in this class
Ø it is used inside the method, that is, the reference of the object to which the method belongs;
Ø it is used inside the constructor to represent the object that the constructor is initializing.
Ø this represents the current object and can call the properties, methods and constructors of the class
Ø use this to call other constructors in this class to ensure that at least one constructor does not use this.
Ø this is a keyword in Java that represents an object. This can appear in instance methods and constructor methods, but not in class methods.
When this keyword appears in the constructor of a class, it represents the object created by the constructor
Ø when this keyword appears in the instance method, this represents the current object calling the method.
static { System.out.println("I am a static code block!!!!!! So I can't use it this~" + name); }
3. Keyword super
Use super in the Java class to call the specified operation in the parent class:
Ø super can be used to access the properties defined in the parent class
Ø super can be used to call member methods defined in the parent class
super can be used to call the constructor of the parent class in the subclass construction method.
be careful:
Ø in particular, super can be used to distinguish when a child parent class has a member with the same name
The traceability of super is not limited to the direct parent class
Ø the usage of super is similar to this. This represents the reference of this class object, and super represents the identification of the memory space of the parent class
1.super, compared with the keyword this, can modify attributes, methods and constructors
2.super modify attributes and methods: in subclass methods and constructors, through super Attribute or super Method to explicitly call the specified property or method of the parent class. In particular, when the subclass and the parent class have properties, or methods with the same name, super must be used when calling the structure in the parent class
3., through the super (formal reference list), explicitly call the constructor specified by the parent class in the subclass constructor.
4. Use super to operate hidden member variables and methods
5. Subclasses can hide member variables and methods inherited from the parent class. If you want to use member variables or methods hidden by subclasses in subclasses, you can use the keyword super. For example, super x,super.play() is to access and call the member variable x and method play() hidden by the subclass
class Person { protected String name="Zhang San"; protected int age; public String getInfo() { return "Name: " + name + "\nage: " + age; } } class Student extends Person { protected String name = "Li Si"; private String school = "New Oriental"; public String getSchool(){ return school; } public String getInfo() { return super.getInfo() +"\nschool: " +school; } } public class TestStudent{ public static void main(String[] args){ Student st = new Student(); System.out.println(st.getInfo()); } } Output is: Name: Zhang San age: 0 school: New Oriental
Call the constructor of the parent class
l all constructors in the subclass will access the constructor of the null parameter of the parent class by default
l when there is no constructor with empty parameters in the parent class, the constructor of the child class must call the corresponding constructor in this class or parent class through this (parameter list) or super (parameter list) statement. At the same time, you can only "choose one from two" and must be placed in the first line of the constructor
l if the subclass constructor does not explicitly call the constructor of the parent class or this class, and there is no parameterless constructor in the parent class, there is a compilation error
Example of calling parent class constructor
4. The difference between this and super
No. | Distinguishing points | this | super |
---|---|---|---|
1 | Access properties | Access the attribute in this class. If this class does not have this attribute, continue to find it from the parent class | Direct access to properties in the parent class |
2 | Call method | Access the method in this class. If this class does not have this method, continue to find it from the parent class | Direct access to methods in the parent class |
3 | Invoking Constructors | Calling this class constructor must be placed on the first line of the constructor | Calling the parent class constructor must be placed on the first line of the child class constructor |
4 | special | Represents the current object | No such concept |
4-10 Keywords: use of package and import
Keyword - package
l package statement, as the first statement of the Java source file, indicates the package of the class defined in the file. (if this statement is defaulted, it is specified as nameless package). Its format is: package top-level package name Sub package name;
l declare the package where the source file is located and write it in the first line of the program. Every Once, it represents a layer of file directory. The package corresponds to the directory of the file system. In the package statement, use To indicate the hierarchy of packages (directories); Baotong usually uses lowercase words, and the first letter of class name is usually capitalized.
l package corresponds to the directory of the file system. In the package statement, use To indicate the hierarchy of package * * (directory) * *;
l packets are usually identified by lowercase words. Usually use the inversion of your company's domain name: com atguigu. xxx
Function of package:
l packages help manage large software systems: classify classes with similar functions into the same package. For example: MVC design pattern
l packages can contain classes and sub packages, which are divided into project levels for easy management
l solve the problem of class naming conflict
l control access rights
Extended knowledge: MVC design pattern
Keyword - import
be careful:
\1. Use import in the source file to explicitly import the classes or interfaces under the specified package
\2. The declaration is between the declaration of the package and the declaration of the class.
\3. If you need to import multiple classes or interfaces, you can explicitly import multiple import statements in parallel
\4. For example: you can use Java util.* Import all classes or interfaces under util package at one time.
\5. If the imported class or interface is Java Lang package or the current package, you can omit this import statement. (if the imported class is under the java.lang package, such as System String Math, no explicit declaration is required.)
\6. If classes with the same name under different packages are used in the code. Then you need to use the full class name of the class to indicate which class is called.
\7. If you have imported Java Class under package a. If you need to use the classes under the sub package of package a, you still need to import them. (importing java.lang. * can only import all classes or interfaces under lang package, not classes or interfaces under lang sub package)
\8. Use of import static combination: call the static attribute or method under the specified class or interface (import static means importing the static attribute or method of the specified class)
jdk main package introduction
1.java.lang ---- contains some core classes of Java language, such as String, Math, Integer, System and Thread, and provides common functions.
-
java.net ---- contains classes and interfaces that perform network related operations.
-
java.io - contains classes that can provide multiple input / output functions.
-
java.util - contains some utility classes, such as defining system features, collection framework classes of interfaces, and using functions related to date and calendar.
-
java.text ---- contains some Java formatting related classes
-
java.sql ---- contains Java classes / interfaces related to JDBC database programming
-
java.awt --- contains several classes that make up the abstract window toolkits. These classes are used to build and manage the graphical user interface (GUI) of the application.
-
java.applet ---- contains some classes required for applet operation.
5, Object oriented (medium)
5-1 the second feature of object-oriented: Inheritance
Inheritance is a hierarchical model of connecting classes, and allows and encourages the reuse of classes. It provides a way to clearly express commonalities. A new class of an object can be derived from an existing class. This process is called class inheritance.
The new class inherits the characteristics of the original class. The new class is called the derived class (subclass) of the original class, and the original class is called the base class (parent class) of the new class. A derived class can inherit methods and instance variables from its base class, and the class can modify or add new methods to make them more suitable for special needs.
Inheritance is a mechanism for creating new classes from existing classes.
The subclass inherits the member variables of the parent class.
The subclass inherits the methods of the parent class.
In the process of subclass inheritance, variable hiding and method rewriting can be realized.
l why should there be inheritance?
Ø if there are the same attributes and behaviors in multiple classes, extract these contents into a single class, then multiple classes do not need to define these attributes and behaviors, just inherit that class.
l multiple classes here are called subclasses (derived classes), and a single class is called a parent class (base class or superclass). It can be understood as: "subclass is a parent class"
l class inheritance syntax rules: class subclass extensions superclass {}
Role of inheritance:
The emergence of inheritance reduces code redundancy and improves code reusability.
The emergence of inheritance is more conducive to the expansion of functions.
The emergence of inheritance creates a relationship between classes and provides the premise of polymorphism.
Note: don't inherit just to get a function in another class
l child parent class is a relative concept
If a subclass inherits the parent class, it inherits the methods and properties of the parent class.
Ø in subclasses, you can use the methods and properties defined in the parent class, or create new data and methods.
Ø in Java, the inherited keyword uses extends, that is, the subclass is not a subset of the parent class, but an extension of the parent class.
Ø subclasses cannot directly access the member variables and methods of * * (private) * * in the parent class.
Subclass: A
Parent class (or base class SuperClass): B
**Clear: * * when there are private attributes or methods in the parent class, the subclass can also be obtained, but due to the encapsulation design, the subclass cannot be called directly. Subclasses cannot directly access private member variables and methods in the parent class.
l in addition to obtaining the structure of the parent class through inheritance, subclasses can also define their own unique components. Extensions: a subclass is an "extension" of the function of the parent class. It is clear that a subclass is not a subset of the parent class.
l Java only supports single inheritance and multi-layer inheritance, and multiple inheritance is not allowed
Ø a subclass can only have one parent
Ø a parent class can derive multiple subclasses
class SubDemo extends Demo{ } //ok class SubDemo extends Demo1,Demo2...//error
Ø if the subclass and the parent class are not in the same package, the subclass inherits the protected and public member variables of the parent class as the member variables of the subclass, and inherits the protected and public methods of the parent class as the methods of the subclass, and the access rights of the inherited members or methods remain unchanged.
Ø when a subclass creates an object, the construction method of the subclass always calls a construction method of the parent class to complete the creation of the parent class; Then call the subclass's own construction method to complete the creation of the subclass. If the construction method of the subclass does not clearly indicate which construction method of the parent class is used, the subclass will call the construction method without parameters of the parent class
When a subclass creates a subclass object, not only the member variables declared in the subclass are allocated memory, but also all the member variables of the parent class are allocated memory space, but the subclass can only operate on the inherited part of the member variables.
Ø subclasses can operate variables and methods that are not inherited by subclasses through inherited methods
5-2 override / overwrite of methods
In the subclass, you can modify the methods inherited from the parent class as needed, also known as method reset and overwrite. When the program executes, the methods of the subclass will override the methods of the parent class.
requirement:
\1. The method overridden by the subclass must have the same method name and parameter list as the method overridden by the parent class
\2. The return value type of the method overridden by the subclass cannot be greater than the return value type of the method overridden by the parent class
\3. The access permission of the method overridden by the subclass cannot be less than that of the method overridden by the parent class
Ø a subclass cannot override a method declared as private permission in the parent class
\4. The exception thrown by the subclass method cannot be greater than the exception of the overridden method of the parent class
1. Rewritten syntax rules
Ø if the subclass inherits the instance method of the parent class, the subclass has the right to override this method.
Ø method rewriting refers to the definition of a method in a subclass. The type of the method is the same as that of the parent method, or it is the subtype of the type of the parent method, and the name, number of parameters and type of parameters of the method are exactly the same as that of the parent method
2. Purpose of rewriting
Ø subclasses can hide inherited methods through method rewriting, and subclasses can change the state and behavior of their parent class to their own state and behavior through method rewriting.
3. Call of rewritten method
Ø for an object created by a subclass, if the subclass overrides the method of the parent class, the runtime system calls the method overridden by the subclass;
Ø for an object created by a subclass, if the subclass does not override the method of the parent class, the runtime system calls the method inherited by the subclass;
4. Precautions for rewriting
When overriding the method of the parent class, it is not allowed to reduce the access permission of the method, but it can increase the access permission (the access restriction modifiers are public, protected, default and private in the order of access permission from high to low.)
Methods with the same name and parameters in the subclass and parent class must be declared non static (that is, overridden) or static (not overridden) at the same time. Because the static method belongs to a class, the subclass cannot override the method of the parent class.
Example 1:
public class Person { public String name; public int age; public String getInfo() { return "Name: "+ name + "\n" +"age: "+ age; } } public class Student extends Person { public String school; public String getInfo() { //override method return "Name: "+ name + "\nage: "+ age + "\nschool: "+ school; } public static void main(String args[]){ Student s1=new Student(); s1.name="Bob"; s1.age=20; s1.school="school2"; //Name:Bob age:20 school:school2 System.out.println(s1.getInfo()); } } Person p1=new Person(); //Call the getInfo() method of the Person class p1.getInfo(); Student s1=new Student(); //Call getInfo() method of Student class s1.getInfo(); This is a kind of "polymorphism": methods with the same name use different objects to distinguish which method is called.
Example 2:
class Parent { public void method1() {} } class Child extends Parent { //Illegal. The access permission of method1() in the subclass private is weaker than that of the overridden method public private void method1() {} } public class UseBoth { public static void main(String[] args) { Parent p1 = new Parent(); Child p2 = new Child(); p1.method1(); p2.method1(); } }
The difference between method overloading and rewriting
Overload: "two are the same and different": the same class, the same method name, and different parameter lists. Note: method overloading has nothing to do with the return value of the method! Constructors can be overloaded
Rewrite: (premise: on the basis of inheritance, the subclass can reconstruct the method with the same name in the parent class after obtaining the structure of the parent class)
1. Overriding and Overloading of methods are different manifestations of Java polymorphism.
2. Overriding is a manifestation of polymorphism between parent and child classes, and Overloading is a manifestation of polymorphism in a class.
3. If a method defined in a subclass has the same name and parameters as its parent class, we say that the method is overridden.
4. When the subclass object uses this method, it will call the definition in the subclass. For it, the definition in the parent class is masked.
5. If multiple methods with the same name are defined in a class, and they either have different parameter numbers or different parameter types, it is called method overloading.
5-3 subclass object instantiation process
public class TestDog { public static void main(String[] args) { Dog d = new Dog(); d.setAge(10); d.setName("Xiao Ming"); d.setHostName("tearful"); System.out.println("name:" + d.getName() + " age:" + d.getAge() + "hostName:" + d.getHostName()); System.out.println(d.toString()); } } // biology class Creator { private int age; public int getAge() { return age; } public void setAge(int age) { this.age = age; } public Creator() { super(); System.out.println("this is Creator's constructor"); } } // Animals class Animal extends Creator { private String name; public String getName() { return name; } public void setName(String name) { this.name = name; } public Animal() { super(); System.out.println("this is Animal's constructor"); } } // dog class Dog extends Animal { private String hostName; public String getHostName() { return hostName; } public void setHostName(String hostName) { this.hostName = hostName; } public Dog() { super(); System.out.println("this is Dog's constructor"); } }
5-4 object oriented feature 3: polymorphism
Polymorphism means that different kinds of objects are allowed to respond to the same message. The basis of polymorphism is inheritance. Polymorphism includes parametric polymorphism and inclusive polymorphism.
Polymorphic language has the advantages of flexibility, abstraction, behavior sharing and code sharing, which solves the problem of application function homonymy.
Polymorphism means that when a method of a parent class is overridden by its subclass, it can produce its own functional behavior.
Polymorphism is another important feature of object-oriented programming. Subclasses can reflect polymorphism, that is, subclasses can override a method of the parent class according to their own needs. Subclasses can change the state and behavior of the parent class into their own state and behavior through method rewriting.
l polymorphism is the most important concept in object-oriented, which is embodied in two ways in Java:
1. Method overload and overwrite
2. Object polymorphism: the reference of the parent class points to the object of the child class
Ø can be directly applied to abstract classes and interfaces
Note: the polymorphism of subclass objects is not used for attributes.
l Java reference variables have two types: compile time type and runtime type. The compile time type is determined by the type used when declaring the variable, and the runtime type is determined by the object actually assigned to the variable. Abbreviation: when compiling, look at the left; When running, look to the right.
Ø if the compile time type is inconsistent with the run-time type, object polymorphism occurs
Ø in the case of polymorphism, "look at the left": look at the reference of the parent class (the parent class does not have methods unique to the child class)
"Look to the right": look at the objects of the subclass (actually running the method of overriding the parent class by the subclass)
l polymorphism of objects - in Java, objects of subclasses can be used instead of objects of parent classes
Ø a variable can only have one definite data type
Ø a reference type variable may point to (Reference) many different types of objects
Person p = new Student(); Object o = new Person();//Variable o of type Object, pointing to Object of type Person System.out.println(o);//Person@69d0a921 o = new Student(); //Object type variable o, pointing to Student type object System.out.println(o);//Student@446cdf90
The subclass inherits the parent class
Ø if the subclass overrides the method of the parent class, it means that the method defined in the subclass completely covers the method with the same name in the parent class, and the system will not be able to transfer the method in the parent class to the subclass.
Ø for instance variables, there is no such phenomenon. Even if an instance variable exactly the same as the parent class is defined in the subclass, it is still impossible for this instance variable to overwrite the instance variable defined in the parent class
Polymorphic summary
Polymorphism: it improves the universality of code, which is often called interface reuse
2. The premise of polymorphic use: ① there should be inheritance relationship; ② there should be rewriting of methods
3. Membership method:
Compile time: check whether there is a method called in the class declared by the reference variable.
Ø Runtime: call the overriding method in the class to which the actual new object belongs.
4. Member variables:
Ø it does not have polymorphism. It only depends on the class declared by the reference variable.
1. Upcasting
A subclass can be regarded as a special parent class, so the reference of the parent type can point to the object of the subclass: upcasting.
//Class A is the parent class of class B. when an object is created with a subclass and the reference of this object is placed in the object of the parent class, object a is called the upper transformation object of object B, for example: A a; a=new B(); or A a; B b=new B(); a=b;
If a reference type variable is declared as the type of the parent class, but actually refers to the subclass object, the variable can no longer access the properties and methods added in the subclass, for example:
Student m = new Student(); m.school = "pku"; //Legal. The Student class has a school member variable Person e = new Student(); e.school = "pku"; //Illegal. The Person class has no school member variable //The attribute is determined at compile time. At compile time, e is of Person type and there is no school member variable, so there is a compilation error.
Examples of polymorphism applications:
//The formal parameter type declared by the method is the parent type. You can use the object of the subclass as the argument to call the method public class Test{ public void method(Person e) { //...... e.getInfo(); } public static void main(Stirng args[]){ Test t = new Test(); Student m = new Student(); t.method(m); //The object m of the subclass is passed to the parameter e of the parent type } }
Use of transformation objects on
1. The upper transformation object cannot operate the new member variables of the subclass; Methods added by subclasses cannot be called.
2. The upper transformation object can access the member variables inherited or hidden by the subclass, and can also call the methods inherited by the subclass or the instance methods overridden by the subclass.
3. If the subclass overrides an instance method of the parent class, when the instance method is called with the transformation object, the instance method overridden by the subclass must be called.
Example 1
class Anthropoid ape { void crySpeak(String s) { System.out.println(s); } } class People extends Anthropoid ape { void computer(int a,int b) { int c=a*b; System.out.println(c); } void crySpeak(String s) { System.out.println("***"+s+"***"); } } public class Example5_10 { public static void main(String args[]) { Anthropoid ape monkey; People geng = new People(); //monkey is the transformation object of People object geng monkey = geng ; //The upper transformation object cannot operate the new member variables of the subclass; Methods added by subclasses cannot be called. //monkey.computer("I love this game"); // You can't write that //The upper transformation object can access the member variables inherited or hidden by the subclass, and can also call the methods inherited by the subclass or the instance methods overridden by the subclass. //If the subclass overrides an instance method of the parent class, when the instance method is called with the transformation object, the instance method overridden by the subclass must be called. monkey.crySpeak("I love this game"); People people=(People)monkey; people.computer(10,10); } }
The output result is
***I love this game*** 100
Example 2
//Abstract classes encapsulate two behavior standards abstract class GirlFriend { abstract void speak(); abstract void cooking(); } class ChinaGirlFriend extends GirlFriend { void speak(){ System.out.println("Hello"); } void cooking(){ System.out.println("Sliced Fish in Hot Chili Oil"); } } class AmericanGirlFriend extends GirlFriend { void speak(){ System.out.println("hello"); } void cooking(){ System.out.println("roast beef"); } } class Boy { GirlFriend friend; void setGirlfriend(GirlFriend f){ friend = f; } void showGirlFriend() { friend.speak(); friend.cooking(); } } public class Example5_12 { public static void main(String args[]) { GirlFriend girl = new ChinaGirlFriend(); Boy boy = new Boy(); boy.setGirlfriend(girl); boy.showGirlFriend(); //girl is the object of transformation girl = new AmericanGirlFriend(); boy.setGirlfriend(girl); boy.showGirlFriend(); } }
The output result is
Hello Sliced Fish in Hot Chili Oil hello roast beef
2. Downcasting
① The opposite of upward transformation is to turn the parent object into a child object. Transition down, use strong conversion character: ()
② In order to ensure that ClassCastException is not reported, it is best to make a judgment before the downward Transformation: instanceof
Father f1 = new Father() Son s1 = (Son)f1; // This is called downcasting // If a is an instance of class A, then a must also be an instance of the parent class of class A. if (p1 instanceof Woman) { System.out.println("hello!"); Woman w1 = (Woman) p1; w1.shopping(); } if (p1 instanceof Man) { Man m1 = (Man) p1; m1.entertainment(); }
3. Virtual method invocation
4.instanceof operator
x instanceof A: check whether x is an object of class A, and the return value is boolean.
Ø it is required that the class to which x belongs and class A must be the relationship between subclass and parent class, otherwise compilation error.
Ø if x belongs to subclass B of class A, the value of x instanceof A is also true.
public class Person extends Object {...} public class Student extends Person {...} public class Graduate extends Person {...} ---------------------------------------------- public void method1(Person e) { if (e instanceof Person) // Handling objects of the Person class and its subclasses if (e instanceof Student) //Handle Student class and its subclass objects if (e instanceof Graduate) //Handle the Graduate class and its subclass objects }
5. Object type conversion (Casting)
Casting of basic data type:
Automatic type conversion: small data types can be automatically converted into large data types
For example, long = 20; double d=12.0f
Mandatory type conversion: large data types can be cast into small data types
For example, float f=(float)12.0; int a=(int)1200L
Casts on Java objects are called shapes
Ø type conversion from subclass to parent class can be performed automatically
Ø type conversion from parent class to child class must be realized through modeling (forced type conversion)
Conversion between reference types without inheritance is illegal
Ø before modeling, you can use the instanceof operator to test the type of an object
Object type conversion example
Example 1
Example 2
public class ConversionTest2{ public void method(Person e) {//Let there be no getschool() method in the Person class // System.out.pritnln(e.getschool()); // Illegal, compile time error if(e instanceof Student){ Student me = (Student)e; //Cast e to Student type System.out.pritnln(me.getschool()); } } public static void main(Stirng args[]){ Test t = new Test(); Student m = new Student(); t.method(m); } }
5-5 object oriented feature 4: abstraction
Abstraction is to ignore those aspects of a topic that are not related to the current goal, so as to pay more attention to those aspects related to the current goal. Abstract does not intend to understand all the problems, but only select some of them without some details for the time being. Abstraction includes two aspects: process abstraction and data abstraction.
5-6 use of object class
Constructor of Object class with only one null parameter public Object() {}
Main methods in Object class:
NO. | Method name | type | describe |
---|---|---|---|
1 | public Object() | structure | Construction method |
2 | public boolean equals(Object obj) | ordinary | Object comparison |
3 | public int hashCode() | ordinary | Get Hash code |
4 | public String toString() | ordinary | Called when the object is printed |
==Operators and equals methods
equals Comparison method: 1.Basic data type: judge whether it is equal according to the value of basic data type. Equal return true,Conversely, return false Note: the data types at both ends can be different, and can also be returned under different circumstances true. 2.Reference data type: compare whether the address values of reference type variables are equal.
Principles for overriding the equals() method
l symmetry: if x.equals(y) returns true, then y.equals(x) should also return true.
Reflexivity: x.equals(x) must return true.
Transitivity: if x.equals(y) returns true and y.equals(z) returns true, then z.equals(x) should also return true.
l consistency: if x.equals(y) returns true, as long as the contents of X and Y remain unchanged, no matter how many times you repeat x.equals(y), the return is true.
l in any case, x.equals(null) always returns false; x. Equals (objects of different types from x) always returns false.
==The difference between and equals
1 = = you can compare both basic types and reference types. For the basic type, it is the comparison value, and for the reference type, it is the comparison memory address
2 equals, it belongs to Java The default method of this class is * *. Lang =, if it is not overridden; We can see that the equals method of String and other classes has been rewritten, and String classes are used more in daily development. Over time, the wrong view that equals * * is a comparative value has been formed.
3. It depends on whether the equals method of Object is overridden in the user-defined class.
4 generally, overriding the equals method will compare whether the corresponding attributes in the class are equal.
toString() method
When we output a reference to an object, the toString() method is called.
1.public String toString() { return getClass().getName() + "@" + Integer.toHexString(hashCode()); } When we didn't rewrite Object Class toString()Method, the class of the object and the position of the object entity in the heap space are printed 2.Generally, we need to rewrite Object Class toString()Method to return each property value of this object. 3.image String Class Date,File Class and wrapper class are rewritten toString()method.
5-7 use of wrappers
Because the basic data type is not a class, it cannot use a large number of methods provided in the java class library. Therefore, in the design, we make each basic data type correspond to a class, and the scope of data storage remains unchanged.
At this time, the basic data type has the characteristics of classes, which are wrapper classes (wrapper or encapsulation classes)
To master:
Conversion between basic data type, packing class and String class!
1.The basic data types and corresponding packaging classes include automatic packing and automatic unpacking For example: int i = 10; Integer i1 = i;//Automatic packing int j = i1;//Automatic unpacking 2.Basic data type and package type---->String Classes: calling String Class overloaded valueOf(Xxx xx); String class---->Basic data type and wrapper class: call the corresponding wrapper parseXxx(String str); be careful: String str = "123"; int i = (int)str; This is the wrong conversion.
Define the corresponding reference types for eight basic types - wrapper class (wrapper class). With the characteristics of the class, you can call the methods in the class. Java is the real object-oriented
//The most commonly used wrapper class in practical development is that the string becomes the basic data type. String str1 = "30" ; String str2 = "30.3" ; int x = Integer.parseInt(str1) ; // Change string to int System.out.println(x); //30 float f = Float.parseFloat(str2) ; // Change string to float type System.out.println(f);//30.3
Boxing and UnBoxing
Conversion between basic type, wrapper class and String class
Packaging usage
6, Object oriented (Part 2)
6-1 keyword: static
Scope of use: static, static. In Java classes, static can be used to modify attributes, methods, code blocks (or initialization blocks) and internal classes
The decorated members have the following characteristics:
Ø load with class loading
Ø prior to object existence
A member that is decorated and is shared by all objects
Ø when the access permission allows, you can directly be called by the class without creating an object
static modifier attribute (class variable (class attribute)):
1. All objects created by the class share this property
2. When one object modifies this property, it will cause another object to call this property. vs instance variable (non static modified attribute, each object has a set of copies)
3. Class variables are loaded with the loading of the class, and they are unique
4. Static variables can be passed directly through classes Class variable
5. Class variables are loaded earlier than objects. So when there is an object, you can use it Class variable use. But class Instance variables do not work.
6. Class variables exist in static fields.
static modifier method (class method):
1. As the class is loaded, it is also the only one in memory
2. You can use the class directly Class method
3. Internally, you can call static properties or static methods, but not non static properties or methods. Conversely, non static methods can call static properties or static methods
be careful:
The life cycle of static structures (static attributes, methods, code blocks, internal classes) is earlier than that of non static structures, and it is recycled later than that of non static structures
this or super keywords are not allowed in static methods!
1. Class variable (class attribute class Variable)
Class variables (class attributes) are shared by all instances of the class (class attributes are variables shared among objects of the class.)
Application examples of class variables
class Person { private int id; public static int total = 0; public Person() { total++; id = total; } public static void main(String args[]){ Person Tom=new Person(); Tom.id=0; total=100; // Static members can be accessed without creating objects } } public class OtherClass { public static void main(String args[]) { Person.total = 100; // Static members can be accessed without creating objects //Access method: class name Class attribute, class name Class method System.out.println(Person.total); //Output 100 Person c = new Person(); System.out.println(c.total); //Output 101 } }
Memory parsing of class variables and instance variables
Memory parsing of static variables
2. Class method
When there is no instance of an object, you can use the class name Access the class method marked by static in the form of method name ().
Inside the static method, you can only access the static attribute of the class, not the non static attribute of the class.
class Person { private int id; private static int total = 0; public static int getTotalPerson() { //id++; // illegal return total; } public Person() { total++; id = total; }} public class TestPerson { public static void main(String[] args) { System.out.println("Number of total is " +Person.getTotalPerson()); //Static methods can be accessed without creating objects Person p1 = new Person(); System.out.println( "Number of total is "+ Person.getTotalPerson()); } } Output is: Number of total is 0 Number of total is 1
l because the static method can be accessed without an instance, there can be neither this nor super inside the static method
l overloaded methods need to be static or non static at the same time
l static modified methods cannot be overridden
class Person { private int id; private static int total = 0; public static void setTotalPerson(int total){ this.total=total; //Illegal. this or super cannot be present in static method } public Person() { total++; id = total; } } public class TestPerson { public static void main(String[] args) { Person.setTotalPerson(3); } }
3. Singleton design mode
l design pattern is the code structure, programming style and thinking way to solve problems after summarizing and theorizing in a large number of practice. The design of mold eliminates our own thinking and exploration. It's like a classic chess score. We use different chess scores for different chess games.
l the so-called class singleton design pattern is to take certain methods to ensure that there can only be one object instance for a class in the whole software system, and the class only provides a method to obtain its object instance.
l if we want a class to generate only one object in a virtual machine, we must first set the access permission of the class constructor to private. In this way, we can't generate the class object outside the class with the new operator, but we can still generate the class object inside the class.
l because you can't get the object of the class from the outside of the class, you can only call a static method of the class to return the object created inside the class. The static method can only access the static member variables in the class. Therefore, the variables pointing to the object of the class generated inside the class must also be defined as static.
Singleton design pattern - Hungry Chinese style
//Hungry Han style 1 class Bank{ //1. Privatization constructor private Bank(){} //2. Provide an instance of the current class internally (create the object of the class, set it to private, and call it through public, reflecting encapsulation) //4. This object must also be static (this instance must also be static) private static Bank instance = new Bank(); //3. Provide a public static method to return the object of the current class public static Bank getInstance(){ return instance; } }
//Hungry Han style 2 class Bank{ //1. Privatization constructor private Bank(){} //2. Create class objects and set them to private, which can be called through public, reflecting encapsulation //4. This object is also required to be static private static Bank instance = null; static{ instance = new Bank(); } //3. This public method must be static public static Bank getInstance(){ return instance; } }
class Single{ //The constructor of private cannot create objects of this class outside of the class private Single() {} //Private, which can only be accessed inside the class private static Single onlyone = new Single(); //getSingle() is static and can be accessed without creating an object public static Single getSingle() { return onlyone; } } public class TestSingle{ public static void main(String args[]) { Single s1 = Single.getSingle(); //Accessing static methods Single s2 = Single.getSingle(); if (s1==s2){ System.out.println("s1 is equals to s2!"); } } }
Singleton design pattern - lazy
class Bank{ private Bank(){} private static Bank instance = null; public static Bank getInstance(){ if(instance == null){//There may be thread safety problems! instance = new Bank(); } return instance; } }
class Singleton{ //1. Privatize the constructor to ensure that the constructor of this class cannot be called outside this class. private Singleton(){ } //2. Reference to the declaration category //4. You also need to use static to modify the reference of this class. private static Singleton instance = null; //3. Set public methods to access class instances public static Singleton getInstance(){ //3.1 if instances of a class are not created, those instances must be created first and then returned to the caller: this class. Therefore, static modification is needed. if(instance == null){ instance = new Singleton(); } //3.2 if there is an instance of a class, it will be returned directly to the caller. return instance; } }
Singleton design pattern - application scenario
The counter of the website is generally implemented in single instance mode, otherwise it is difficult to synchronize.
Ø the log application of the application is generally implemented in the single instance mode. This is generally because the shared log file is always open, because there can only be one instance to operate, otherwise the content is not easy to add.
Ø the design of database connection pool generally adopts single instance mode, because database connection is a kind of database resource.
Ø in the project, there is usually only one object for the class reading the configuration file. There is no need to generate an object to read every time the configuration file data is used.
Ø Application is also a typical Application of single example
Task Manager of Windows is a typical singleton mode
Ø the Recycle Bin of Windows is also a typical single case application. During the operation of the whole system, the Recycle Bin has maintained only one instance.
Advantages of singleton mode
Since the singleton mode only generates one instance, the system performance overhead is reduced. When the generation of an object requires more resources, such as reading the configuration and generating other dependent objects, it can be solved by directly generating a singleton object when the application is started, and then permanently residing in memory.
For more explanations on the singleton mode, you can go to my other blogs, Click to go
6-2 understand the syntax of main method
l because the Java virtual machine needs to call the main() method of the class, the access permission of the method must be public. Because the Java virtual machine does not need to create an object when executing the main() method, the method must be static. The method receives a set of parameters of String type, and the array stores the parameters passed to the running class when executing the Java command.
l and because the main() method is static, we cannot directly access the non static members in the class. We must create an instance object of the class before we can access the non static members in the class through this object. We have encountered this situation many times in the previous examples.
public static void main(String[] args){ //Method body } //1.main() is a method, the main method, and the entry of the program //2. Permission modifier: public protected, default private --- object-oriented encapsulation //3. For methods: static final abstract //4. Return value of method: void / specific return value type (basic data type & reference data type). There must be return inside the method //Naming rule: yyxzz. When naming a method, see the meaning of the name //6. Formal parameter list: multiple methods of formal parameter list with different names of the same method constitute overloading. Formal parameter & argument -- parameter transfer mechanism of method: value transfer //7. Method body: a method defines a function, and the specific implementation is operated by the method body.
The fourth member of class 6-3: code block (initialization block)
Static and non static code blocks
An initialization block in a class can only be modified if it has modifiers static Modifier, called static code block(static block ), When a class is loaded, the declaration of class attributes and static code blocks are executed in sequence and only once. Static code blocks: Using static Decorated code block 1.There can be output statements. 2.You can initialize class properties and class declarations. 3.Non static properties cannot be initialized. That is: non static properties and methods cannot be called. 4.If there are multiple static code blocks, they are executed from top to bottom. 5.Static code blocks are executed before non static code blocks. 6.Static code blocks are loaded as the class is loaded and executed only once. Non static code block: None static Decorated code block 1.There can be output statements. 2.You can initialize class properties and class declarations. 3.In addition to calling non static structures, you can also call static variables or methods. 4.If there are multiple non static code blocks, they are executed from top to bottom. 5.It is executed every time an object is created. And executed before the constructor
Static initialization block example
class Person { public static int total; static { total = 100; System.out.println("in static block!"); } } public class Test { public static void main(String[] args) { System.out.println("total = "+ Person.total); //When a class is loaded, the declaration of class attributes and static code blocks are executed in sequence and only once. System.out.println("total = "+ Person.total); } } Output: in static block total=100 total=100
Execution order of member variable assignment in program
1. Declare the default initialization of member variables
2. Explicit initialization and multiple initialization blocks are executed in sequence (in sequence at the same level)
3. The constructor then initializes the member
4. By object Property or object Method, you can assign values to attributes multiple times
6-4 keyword: final
**Where is this constant assigned: * * ① this constant cannot be initialized by default ② it can be explicitly assigned, code block and constructor.
Variables are decorated with static final: global constants. For example: PI of Math class
1.final Modifier class final class A{ } class B extends A{ //Error, cannot be inherited. } 2.final Modification method class A{ public final void print(){ System.out.println("A"); } } class B extends A{ public void print(){ //Error, cannot be rewritten. System.out.println(""Silicon Valley"); } } 3.final Modifier variable - constant class A{ private final String INFO = "atguigu"; //declare constant public void print(){ //INFO = "Silicon Valley"// Error, the final modifier can only be assigned a value once } } The constant name should be capitalized and the content cannot be modified—— Like the edict of an ancient emperor. static final: Global constant final Keywords can modify local variables in classes, member variables, and methods. have access to final Declare a class as final Class. final Class cannot be inherited, that is, it cannot have subclasses. For example: final class A { ... ... } If used final Modify a method in the parent class, then this method does not allow subclasses to override. If a member variable or local variable is modified to final Yes, it's a constant
Keyword final application example
6-5 abstract classes and abstract methods
With the definition of new subclasses in the inheritance hierarchy, the class becomes more and more specific, while the parent class is more general and general. Class design should ensure that parent and child classes can share features. Sometimes a parent class is designed so abstract that it has no concrete instance. Such a class is called an abstract class.
Abstract classes are classes used to model objects whose parent class cannot determine all implementations, but whose child classes provide concrete implementations.
//Abstract classes encapsulate two behavior standards abstract class GirlFriend { abstract void speak(); abstract void cooking(); }
1.abstract Decoration class: Abstract column Abstract classes have the following characteristics: 1.Compared with ordinary classes, abstract Class can have abstract method. Or not. about abstract Method, only declaration is allowed, implementation is not allowed, and use is not allowed final modification abstract method. 2.about abstract Class, cannot be used new Operator to create an object of this class, only its subclasses can be generated, and objects are created by subclasses. 3.If a class is abstract Class, which must concretely implement all the functions of the parent class abstract method. 4.Cannot be instantiated 5.Abstract classes have constructors (Every class has a constructor) 6.The class of the abstract method must be an abstract class. 7.Abstract classes can have no abstract methods. When we design a class and do not need to create instances of this class, we can consider setting it as abstract, After the abstract method of this class is implemented by its subclass, it can be instantiated 2.abstract Modification method: abstract method 1)Format: no method body, including{}.For example: public abstract void eat(); 2)The abstract method only retains the function of the method, and the specific execution is handed over to the subclass of the inherited abstract class, which overrides the abstract method. 3)If a subclass inherits an abstract class and rewrites all abstract methods, this class is a"Entity class",That is, it can be instantiated 4)If a subclass inherits an abstract class and does not override all abstract methods, which means that there are still abstract methods in this class, this class must be declared abstract! abstract class A{ abstract void m1( ); public void m2( ){ System.out.println("A Class m2 method"); } } class B extends A{ void m1( ){ System.out.println("B Class m1 method"); } } public class Test{ public static void main( String args[ ] ){ A a = new B( ); a.m1( ); a.m2( ); } }
Application of polymorphism: template method
Abstract class embodies the design of a template pattern. Abstract class is the general template of multiple subclasses. Subclasses expand and transform on the basis of abstract class, but subclasses will retain the behavior of abstract class as a whole.
Problems solved:
Ø when part of the internal implementation of the function is determined, part of the implementation is uncertain. At this time, you can expose the uncertain part and let the subclass implement it.
In other words, when implementing an algorithm in software development, the overall steps are very fixed and general, and these steps have been written in the parent class. However, some parts are changeable, and the changeable parts can be abstracted for different subclasses to implement. This is a template mode.
give an example
Template method design pattern is often used in programming. His shadow can be found in various frameworks and class libraries. For example, the common ones are:
l encapsulation of database access
l Junit unit test
L about doGet/doPost method call in Java Web Servlet
L template program in Hibernate
Spring, etc
6-6 interface
l the essence of an interface is a contract, standard and specification. Just like our laws, everyone should abide by them after they are formulated.
l in order to overcome the shortcomings of Java single inheritance, Java uses interfaces, and a class can implement multiple interfaces. With an interface, you can get the effect of multiple inheritance.
l use the keyword interface to define an interface. The definition of interface is very similar to that of class, which is divided into interface declaration and interface body.
1. Interface declaration
Interfaces are declared by using the keyword interface
Format: name of interface
2. Interface body
The interface body contains two parts: constant definition and method definition. Only the method declaration is allowed in the interface body, and the method implementation is not allowed. Therefore, the method definition has no method body and uses a semicolon; ending.
An interface is a collection of definitions of abstract methods and constant values. In essence, an interface is a special abstract class. This abstract class only contains the definitions of constants and methods, without the implementation of variables and methods.
l implement interface classes:
class SubClass implements InterfaceA{ }
A class can implement multiple interfaces, and interfaces can also inherit other interfaces.
be careful: All variables in the interface are by default public static final In the interface, only abstract Method, there is no ordinary method, and the access rights of all methods are by default public Methods in interfaces cannot be static and final Modify, because you want to override the methods in all interfaces. There is no constructor in the interface. Interfaces can generate new interfaces through inheritance. Similar to inheritance, there is polymorphism between interface and implementation class The main purpose of the interface is to be implemented by the implemented class. (interface oriented programming) The class implementing the interface must provide the specific implementation contents of all methods in the interface before instantiation. Otherwise, it is still an abstract class. Java The interfaces provided are in the corresponding packages through import Statement can introduce not only classes in the package, but also interfaces in the package, for example:import java.io.*; definition Java Syntax format of class: write first extends,Post writing implements class SubClass extends SuperClass implements InterfaceA{ } A class uses keywords implements Declare that you implement one or more interfaces. For example: class A implements Printable,Addable If a non abstract class implements an interface, the class must override all methods of the interface. Interface and class are parallel, or can be understood as a special class. In essence, an interface is a special abstract class, This abstract class contains only the definitions of constants and methods(JDK7.0 And before),There is no implementation of variables and methods.
interface is a concept parallel to class
1. Interface can be regarded as a special abstract class. It is a collection of constants and abstract methods. It cannot contain variables and general methods.
2. The interface has no constructor.
3. An interface defines a function. This function can be implemented by classes.
For example: class CC extensions DD implements AA
4. The class that implements the interface must override all the abstract methods before it can be instantiated. If you do not override all abstract methods, this class is still an abstract class
5. Class can implement multiple interfaces---- The inheritance of classes in java is single inheritance
6. The relationship between interfaces is also inheritance, and multiple inheritance can be realized
7. There are also polymorphisms between interfaces and specific implementation classes
Comparison between interface and abstract class
In development, we often see that a class does not inherit an implemented class, but either inherits an abstract class or implements an interface.
The comparison between interface and abstract class is as follows:
1. Abstract classes and interfaces can have abstract methods.
2. The interface can only have constants, not variables; The abstract class can have both constants and variables.
3. There can also be non abstract methods in the abstract class, and the interface cannot.
No. | Distinguishing points | abstract class | Interface |
---|---|---|---|
1 | definition | A class that contains an abstract method | Collection of abstract methods and global constants |
2 | form | Construction method, abstract method, ordinary method, constant, variable | Constants, abstract methods |
3 | use | Subclasses inherit abstract classes (extensions) | Subclass implements interfaces |
4 | relationship | Abstract classes can implement multiple interfaces | Interfaces cannot inherit abstract classes, but multiple interfaces are allowed |
5 | Common design patterns | Template design | Factory design, agent design |
6 | object | Instantiated objects are generated through the polymorphism of objects | |
7 | limit | Abstract classes have the limitation of single inheritance | The interface has no such limitation |
8 | actual | As a template | Is it a standard or a capability |
9 | choice | If both abstract classes and interfaces can be used, the interface is preferred because the limitation of single inheritance is avoided | |
10 | special | An abstract class can contain multiple interfaces, and an interface can contain multiple abstract classes |
Interface callback
Interface callback means that the reference of the object created by the class implementing an interface can be assigned to the interface variable declared by the interface, and the interface variable can call the interface method rewritten by the class. In fact, when an interface variable calls an interface method overridden by a class, it notifies the corresponding object to call this method.
//analysis: Com com;//Declare interface object ImpleCom obj= new ImpleCom();//Implement interface subclass objects com = obj; //Interface callback interface ShowMessage { void Display trademark(String s); } class TV implements ShowMessage { public void Display trademark(String s) { System.out.println(s); } } class PC implements ShowMessage { public void Display trademark(String s) { System.out.println(s); } } public class Example6_2 { public static void main(String args[]) { ShowMessage sm; //Declare interface variables sm=new TV(); //Reference of object stored in interface variable sm.Display trademark("Great wall TV"); //Interface callback. sm=new PC(); //Reference of object stored in interface variable sm.Display trademark("Lenovo to the moon 5008 PC machine"); //Interface callback } } Output is: Great wall TV Lenovo to the moon 5008 PC machine
Design pattern of factory method
//Application of interface: design pattern of factory method public class TestFactoryMethod { public static void main(String[] args) { IWorkFactory i = new StudentWorkFactory(); i.getWork().doWork(); IWorkFactory i1 = new TeacherWorkFactory(); i1.getWork().doWork(); } } interface IWorkFactory{ Work getWork(); } class StudentWorkFactory implements IWorkFactory{ @Override public Work getWork() { return new StudentWork(); } } class TeacherWorkFactory implements IWorkFactory{ @Override public Work getWork() { return new TeacherWork(); } } interface Work{ void doWork(); } class StudentWork implements Work{ @Override public void doWork() { System.out.println("Students do their homework"); } } class TeacherWork implements Work{ @Override public void doWork() { System.out.println("The teacher marked the homework"); } } Output is: Students do their homework The teacher marked the homework
Application of interface: proxy mode
Proxy pattern is a design pattern that is widely used in Java development. Proxy design is to provide a proxy for other objects to control access to this object.
//Application of interface: proxy mode (static proxy) public class TestProxy { public static void main(String[] args) { Object obj = new ProxyObject(); obj.action(); } } interface Object{ void action(); } //proxy class class ProxyObject implements Object{ Object obj; public ProxyObject(){ System.out.println("Agent class created successfully"); obj = new ObjctImpl(); } public void action(){ System.out.println("The proxy class starts executing"); obj.action(); System.out.println("End of proxy class execution"); } } //Proxy class class ObjctImpl implements Object{ @Override public void action() { System.out.println("=====The proxy class starts executing======"); System.out.println("=====Specific operation======"); System.out.println("=====The execution of the proxy class is completed======"); } }
Output is:
Agent class created successfully The proxy class starts executing =====The proxy class starts executing====== =====Specific operation====== =====The execution of the proxy class is completed====== End of proxy class execution
Interface improvement in Java 8
In Java 8, you can add static methods and default methods for interfaces. From a technical point of view, this is completely legal, but it seems to violate the concept of interface as an abstract definition.
Static method: use static keyword to modify. You can call static methods directly through the interface and execute their method bodies. We often use static methods in classes that we use together. You can find paired interfaces and classes like Collection/Collections or Path/Paths in the standard library.
Default method: the default method is decorated with the default keyword. Can be called by implementing class objects. While providing new methods in the existing interfaces, we also maintain the compatibility with the old version code. For example, the java 8 API provides rich default methods for interfaces such as Collection, List and Comparator.
Default method in interface
l if a default method is defined in one interface and a method with the same name and parameters is also defined in another interface (whether this method is the default method or not), interface conflict will occur when the implementation class implements the two interfaces at the same time.
Ø solution: the implementation class must override the methods with the same name and parameters in the interface to solve the conflict.
l if a default method is defined in an interface and a non abstract method with the same name and parameters is also defined in the parent class, there will be no conflict. Because the principle of class priority is followed at this time. Default methods with the same name and parameters in the interface are ignored.
Interface conflict resolution
Internal member 5 of category 6-7: internal category
l when there is an internal part of a thing that needs a complete structure to describe, and this internal complete structure only provides services for external things, then the whole internal complete structure is best to use internal classes.
l in Java, the definition of one class is allowed to be located inside another class. The former is called internal class and the latter is called external class. (Java supports declaring another class in one class. Such a class is called an inner class, and the class containing the inner class becomes the embedded class of the inner class.)
l Inner class is generally used within the class or statement block that defines it. When it is referenced externally, it must be given a complete name.
Ø the name of the Inner class cannot be the same as the name of the external class containing it;
Ø Inner class can use the private data of the external class because it is a member of the external class and members of the same class can access each other. To access the members of the Inner class, the outer class needs: the Inner class Member or Inner class object Members.
l classification: member inner class (divided into static member inner class and non static member inner class)
Local inner classes (not to mention modifiers)
Anonymous inner class
Usage rules of internal classes:
Declaring an inner class is like declaring a method or variable in a class. A class regards the inner class as its own member.
In the class body of an embedded class, the object declared by the inner class can be used as a member of the embedded class.
The member variables of the embedded class are still valid in the inner class, and the methods in the inner class can also call the methods in the embedded class.
Class variables and class methods cannot be declared in the class body of an internal class.
/*When compiling, the embedded class and the inner class generate two Class file. RedCowForm.class RedCowForm$RedCow.class */ public class RedCowForm { static String formName; RedCow cow; //Inner class declaration object RedCowForm() {} RedCowForm(String s) { cow = new RedCow(150,112,5000); formName = s; } public void showCowMess() { cow.speak(); } class RedCow { //Internal class start String cowName = "Red Bull"; int height,weight,price; RedCow(int h,int w,int p){ height = h; weight = w; price = p; } void speak() { System.out.println("I am"+cowName+",height:"+height); } } //End of inner class }
1. Member internal class
Member inner class example
public class A{ private int s = 111; public class B { private int s = 222; public void mb(int s) { System.out.println(s); // Local variable s System.out.println(this.s); // Properties of internal class object s System.out.println(A.this.s); // Outer class object attribute s } } public static void main(String args[]){ A a = new A(); A.B b = a.new B(); b.mb(333); } }
Output is:
333 222 111
2. Local internal class
l characteristics of local internal classes
Ø the inner class is still an independent class. After compilation, the inner class will be compiled into an independent class Class file, but preceded by the class name and $symbol of the external class, as well as the numerical number.
Ø it can only be used in the method or code block that declares it, and it is declared before use. This class cannot be used anywhere else.
Ø local inner classes can use members of outer classes, including private ones.
* * local internal classes can use local variables of external methods, but they must be final** It is caused by the different declaration cycles of local internal classes and local variables.
Ø local internal classes are similar to local variables. public,protected, default and private cannot be used
Ø local inner classes cannot be decorated with static, so they cannot contain static members
3. Anonymous class
When creating a subclass object, in addition to using the construction method of the parent class, there is also a class body. This kind of body is considered as a subclass. The class body after removing the class declaration is called an anonymous class.
Assuming that bank is a class, the following code creates an object with a subclass of Bank (anonymous class):
new Bank () { Class body of anonymous class };
An anonymous class related to a class is a subclass of that class. This subclass is not clearly defined by class declaration, so it is called an anonymous class.
An anonymous class related to an interface is a class that implements the interface. This subclass is not clearly defined by a class declaration, so it is called an anonymous class.
Anonymous Inner Class
l anonymous inner class cannot define any static members, methods and classes. Only one instance of anonymous inner class can be created. An anonymous inner class must be behind new, which implicitly implements an interface or class.
l characteristics of anonymous inner classes
Ø anonymous inner class must inherit the parent class or implement the interface
Ø an anonymous inner class can only have one object
Ø anonymous inner class objects can only be referenced in polymorphic form
6-8 assertion statement
Use an array to put the scores of a student's five courses, and the program is ready to calculate the sum of the students' scores. When debugging the program, the assertion statement is used. If the score is found to be negative, the program will immediately end execution.
public static void main (String args[ ]) { int [] score={-120,98,89,120,99}; int sum=0; /* foreach Statement is one of the new features of Java 5. foreach provides great convenience for developers in traversing arrays and collections. foreach Statement is a special simplified version of for statement, but foreach statement cannot completely replace for statement, However, any foreach statement can be rewritten as a version of the for statement. foreach It is not a keyword. It is customary to call this special format of for statement "foreach" statement. Understand foreach from the English literal meaning, that is, the meaning of "for each". Actually, that's what it means. foreach Statement format: for(Element type t element variable x: traversal object obj){ java statements that reference x; } */ for(int number:score) { assert number > 0:"Negative numbers cannot be grades"; sum=sum+number; } System.out.println("Total score:"+sum); }
There are two forms of assertion statement: assert statement uses the following keywords:
assert booleanExpression; assert booleanExpression:messageException; In both expressions, booleanExpression Represents a boolean expression, messageException Represents a basic type or an object(Object), Basic types include boolean,char,double,float,int,long etc. Because all classes are Object So this parameter can be used for all objects.
6-9 understanding of native keyword
7, Exception handling
7-1 exception overview and exception architecture
l exception: in the Java language, abnormal conditions during program execution are called exceptions. (syntax and logic errors in the development process are not exceptions)
L the abnormal events occurred during the execution of Java programs can be divided into two categories:
Ø Error: a serious problem that cannot be solved by the Java virtual machine. Such as: JVM system internal Error, resource exhaustion, StackOverflowError, OOM and other serious situations. Generally, targeted code is not written for processing.
Ø Exception: other general problems caused by programming errors or accidental external factors can be handled with targeted code. For example:
1. Null pointer access
2. An attempt was made to read a file that does not exist
3. Network connection interrupted
4. Array subscript out of bounds
There are generally two solutions to these errors:
One is to terminate the operation of the program in case of an error. Another method is that programmers consider error detection, error message prompt and error handling when writing programs.
l it is ideal to catch errors during compilation, but some errors only occur at run time. For example: divisor is 0, array subscript is out of bounds, etc
Classification:
Compile time exception
Runtime exception
Compile time exception
An exception that the compiler requires to be handled. That is, the general exception caused by external factors when the program is running. The compiler requires that java programs must catch or declare all compile time exceptions. For this kind of exception, if the program does not handle it, it may bring unexpected results
Runtime exception
An exception that the compiler does not require forced handling. Generally refers to the logic error in programming, and programmers should actively avoid its exceptions. java.lang.RuntimeException class and its subclasses are runtime exceptions.
This kind of exception can not be handled, because this kind of exception is very common. If it is fully handled, it may affect the readability and running efficiency of the program.
7-2 common anomalies
7-3 exception handling mechanism 1: try catch finally
|When writing a program, it is often necessary to add the detected code where errors may occur. For example, when performing x/y operation, it is necessary to detect that the denominator is 0, the data is empty, and the input is not data but characters. Too many if else branches will lead to the code lengthening, bloated and poor readability of the program. Therefore, the exception handling mechanism is adopted.
|The exception handling mechanism adopted by Java is to gather the exception handling program code together and separate it from the normal program code, making the program concise, elegant and easy to maintain.
|Java provides a catch and throw model for exception handling.
|If an exception occurs during the execution of a java program, an exception class object will be generated, and the exception object will be submitted to the Java runtime system. This process is called throwing an exception.
|Generation of exception objects
Ø automatically generated by the virtual machine: during the running of the program, the virtual machine detects that there is a problem with the program. If the corresponding handler is not found in the current code, an instance object of the corresponding exception class will be automatically created in the background and thrown - automatically thrown
Ø manually created by developers: Exception exception = new ClassCastException()—— Creating a good exception object without throwing has no impact on the program, just like creating an ordinary object
Exception throwing mechanism
|If an exception is thrown within a method, the exception object will be thrown into the caller's method for processing. If the exception is not handled in the caller method, it continues to be thrown to the upper method of the calling method. This process will continue until the exception is handled. This process is called catch exception.
|If an exception returns to the main() method and the main() does not handle it, the program terminates.
|Programmers usually can only deal with exceptions and can't do anything about errors.
|Information about catching exceptions:
Like other objects, you can access the member variables of an exception object or call its methods.
Ø getMessage() gets the exception information and returns a string
Ø printStackTrace() gets the exception class name and exception information, as well as the location of the exception in the program. The return value is void.
//Exception handling is implemented through the try catch finally statement. try{ ...... //Code that may cause exceptions } catch( ExceptionName1 e ){ ...... //Handling measures when an exception of type ExceptionName1 is generated } catch( ExceptionName2 e ){ ...... //Handling measures when an exception of type ExceptionName2 is generated } finally{ ...... //A statement that is executed unconditionally regardless of whether an exception occurs } try The first step in catching exceptions is to use try{...}The statement block selects the scope of catching exceptions and places the code that may have exceptions in the try In a statement block. catch (Exceptiontype e) stay catch Statement block is the code that handles the exception object. each try A statement block can be accompanied by one or more statements catch sentence, Used to handle different types of exception objects that may be generated. finally The last step in catching exceptions is through finally Statement provides a unified exit for exception handling, The status of other procedures can be controlled uniformly. Whether in try Whether an abnormal event has occurred in the code block, catch Whether the statement is executed, catch Whether the statement has exceptions, catch Whether there is in the statement return,finally All statements in the block are executed. finally Statement and catch The statement is optional If you know exactly what kind of exception is generated, you can use this exception class as catch Parameters of; You can also use its parent class as catch Parameters for. For example: you can use ArithmeticException Class as a parameter, you can use RuntimeException Class as a parameter, Or use the parent class of all exceptions Exception Class as an argument. But not with ArithmeticException Class independent exceptions, as NullPointerException(catch Statements in will not be executed).
7-4 exception handling mechanism 2: throws
Declaration throws an exception
Override the principle of method declaration throwing exception
7-5 throw exception manually
7-6 user defined exception class
l generally, user-defined exception classes are subclasses of RuntimeException.
l custom exception classes usually need to write several overloaded constructors.
l user defined exception needs to provide serialVersionUID
l custom exceptions are thrown through throw.
l the most important thing about custom exceptions is the name of the exception class. When an exception occurs, you can judge the exception type according to the name.
The user-defined exception class MyException is used to describe the error information of the data value range. The user's own exception class must inherit the existing exception class.
7-7 summary: 5 keywords for exception handling
8, Multithreading
8-1 basic concepts: program, process and thread
|A program is a set of instructions written in a certain language to complete a specific task. It refers to a piece of static code, static object.
|A process is an execution process of a program or a running program. It is a dynamic process: it has its own process of emergence, existence and extinction—— life cycle
Ø for example: QQ in operation, MP3 player in operation
Ø the program is static and the process is dynamic
Ø as the unit of resource allocation, the system will allocate different memory areas for each process at run time
|Thread, a process can be further refined into a thread, which is an execution path within a program.
If a process executes multiple threads in parallel at the same time, it supports multithreading
Ø as a unit of scheduling and execution, each thread has an independent running stack and program counter (pc), and the overhead of thread switching is small
Ø multiple threads in a process share the same memory unit (memory address space). They allocate objects from the same heap and can access the same variables and objects. This makes the communication between threads easier and more efficient. However, the shared system resources operated by multiple threads may bring security risks.
l understanding of single core CPU and multi-core CPU
Ø single core CPU is actually a fake multithreading, because only one thread can be executed in a time unit. For example: Although there are multiple lanes, there is only one staff member in the toll station charging. Only after charging can it pass through, so the CPU is like a toll collector. If someone doesn't want to pay, the toll collector can "hang" him (hang him until he has figured it out and has the money ready). But because the CPU time unit is very short, I can't feel it.
Ø if it is multi-core, it can give better play to the efficiency of multithreading. (today's servers are multi-core)
Ø a Java application Exe, in fact, there are at least three threads: main() main thread, gc() garbage collection thread and exception handling thread. Of course, if an exception occurs, it will affect the main thread.
l parallelism and concurrency
Ø parallel: multiple CPU s execute multiple tasks at the same time. For example: many people do different things at the same time.
Concurrency: one CPU (using time slice) executes multiple tasks at the same time. For example: second kill, multiple people do the same thing.
Advantages of multithreaded programs:
1. Improve application response. It is more meaningful to the graphical interface and can enhance the user experience.
2. Improve the utilization of computer system CPU
3. Improve program structure. The long and complex process is divided into multiple threads and run independently, which is conducive to understanding and modification
When do I need multithreading
l the program needs to perform two or more tasks at the same time.
l when the program needs to realize some tasks that need to wait, such as user input, file reading and writing operation, network operation, search, etc.
l when you need some programs running in the background.
8-2 creation and use of threads
Thread creation and startup
|The JVM of the Java language allows programs to run multiple threads through Java Lang. thread class.
|Characteristics of Thread class
Ø each Thread completes its operation through the run() method of a specific Thread object. The body of the run() method is often called the Thread body
Ø start the Thread through the start() method of the Thread object instead of calling run()
1.Thread class
l constructor
Ø Thread(): create a new Thread object
Thread(String threadname): create a thread and specify the thread instance name
Ø Thread(Runnable target): Specifies the target object to create the thread, which implements the run method in the Runnable interface
Ø Thread(Runnable target, String name): create a new Thread object
Related methods of Thread class
l void start(): start the thread and execute the run() method of the object
l run(): the operation performed by a thread when it is scheduled
l String getName(): returns the name of the thread
l void setName(String name): set the thread name
l static Thread currentThread(): returns the current Thread. this is in the Thread subclass, which is usually used for the main Thread and Runnable implementation class
l static void yield(): thread yield
Ø pause the thread currently executing and give the execution opportunity to the thread with the same or higher priority
Ø if there are no threads with the same priority in the queue, this method is ignored
l join(): when the join() method of other threads is invoked in a program execution stream, the calling thread will be blocked until the join thread added by the join() method is executed.
Ø low priority threads can also be executed
L static void sleep (long miles): (specified time: milliseconds)
Ø make the current active thread give up control over the CPU within the specified time period, so that other threads have the opportunity to be executed, and re queue when the time comes.
Ø throw InterruptedException exception
l stop(): force the end of thread life, not recommended
l boolean isAlive(): returns boolean to judge whether the thread is still alive
2. Two ways to create threads in API
l JDK1. There are two ways to create a new execution thread before 5:
How to inherit Thread class
How to implement Runnable interface
1. Inherit Thread class
-
Define subclasses that inherit the Thread class.
2) Override the run method in the Thread class in the subclass.
-
Create a Thread subclass object, that is, create a Thread object.
-
Call the thread object start method: start the thread and call the run method.
l precautions:
\1. If you call the run() method manually, it's just an ordinary method without starting the multithreading mode.
\2. The run () method is called by the JVM. When it is called and the process control is determined by the CPU scheduling of the operating system.
\3. To start multithreading, you must call the start method.
\4. A thread object can only call the start() method once to start. If it is called repeatedly, an exception IllegalThreadStateException will be thrown.
Why should this or super be placed on the first line
this() and super() are used when you want to call other constructors or control parent constructors with the parameters passed into the current constructor or the data in the constructor. In a constructor, you can only use one of this() or super(), and the calling position can only be in the first line of the constructor,
In the subclass, if you want to call the constructor of the parent class to initialize the part of the parent class, call super() with appropriate parameters. If you call the constructor of the parent class with super() without parameters (and do not use this() to call other constructors), the default constructor of the parent class will be called. If the parent class has no default constructor, Then the compiler will report an error.
2. Implement Runnable interface
1) Define subclasses and implement Runnable interface.
2) Override the run method in the Runnable interface in the subclass.
3) Create a Thread object through the Thread class argument constructor.
4) Pass the subclass object of Runnable interface as the actual parameter to the constructor of Thread class.
5) Call the start method of Thread class: start the Thread and call the run method of Runnable subclass interface.
Relationship and difference between thread and runnable
|Difference:
Inherit Thread: Thread code is stored in the run method of Thread subclass.
Implement Runnable: the run method of the subclass of the interface in the thread code.
|Benefits of runnable:
1) avoid the limitation of single inheritance
2) multiple threads can share the object of the same interface implementation class, which is very suitable for multiple threads to process the same resource.
3. Thread scheduling
4. Thread priority
5. Classification of threads
Threads in Java are divided into two categories: one is daemon thread and the other is user thread.
Ø they are the same in almost every way. The only difference is to judge when the JVM leaves.
The guardian thread is used to serve the user thread, and the thread. is invoked before the start() method. A daemon thread can be turned into a daemon thread.
Java garbage collection is a typical daemon thread.
Ø if there are daemon threads in the JVM, the current JVM will exit.
8-3 thread life cycle
|Thread. Is used in JDK The state enumeration represents several states of a thread
|To implement multithreading, you must create a new Thread object in the main Thread. The Java language uses the objects of Thread class and its subclasses to represent threads. In a complete life cycle, it usually experiences the following five states:
Ø new: when the object of a Thread class or its subclass is declared and created, the new Thread object is in the new state
Ready: after the thread in the new state is started (), it will enter the thread queue and wait for the CPU time slice. At this time, it has the conditions to run, but it has not been allocated CPU resources
Run: when the ready thread is scheduled and obtains processor resources, it enters the running state. The run() method defines the operation and function of the thread
Ø blocking: in a special case, when the input / output operation is suspended or executed artificially, give up the CPU and temporarily suspend its execution to enter the blocking state
Ø death: the thread has completed all its work, or the thread is forcibly suspended in advance or terminated due to an exception
8-4 thread synchronization
1. Usage of synchronized
Java provides a professional solution to the security problem of multithreading: synchronization mechanism
1.Synchronous code block synchronized (Object){ // Code to be synchronized; } 2.synchronized It can also be placed in the method declaration to indicate that the whole method is a synchronous method. For example: public synchronized void show (String name){ .... }
2. Scope of synchronization
3. Mutex
In Java language, the concept of object mutex is introduced to ensure the integrity of shared data operation.
Each object corresponds to a tag called mutex, which is used to ensure that only one thread can access the object at any time.
Keyword synchronized to associate with the mutex of the object. When an object is decorated with synchronized, it indicates that the object can only be accessed by one thread at any time.
Limitation of synchronization: the execution efficiency of the program should be reduced
The lock of the synchronization method (non static) is this.
The lock of the synchronous method (static) is the current class itself.
4. Operation of releasing lock
Ø the execution of the synchronization method and synchronization code block of the current thread ends
Ø the current thread encountered a break and return in the synchronization code block and synchronization method, which terminated the code block and the continued execution of the method.
Ø the current thread has an unhandled Error or Exception in the synchronization code block and synchronization method, resulting in an abnormal end
Ø the current thread executes the wait() method of the thread object in the synchronization code block and synchronization method. The current thread pauses and releases the lock.
5. Operation without releasing the lock
|When a thread executes a synchronization code block or synchronization method, the program calls thread sleep(),Thread. The yield () method pauses the execution of the current thread
|When a thread executes a synchronization code block, other threads call the thread's suspend() method to suspend the thread, and the thread will not release the lock (synchronization monitor).
Ø try to avoid using suspend() and resume() to control threads
6. Thread deadlock
Deadlock:
Different threads occupy the synchronization resources needed by the other party and do not give up. They are waiting for the other party to give up the synchronization resources they need, forming a thread deadlock
After a deadlock occurs, there will be no exception or prompt, but all threads are blocked and cannot continue
resolvent:
Special algorithms and principles
Minimize the definition of synchronization resources
Try to avoid nested synchronization
7. Lazy style of singleton design mode (thread safety)
8. Lock
l starting from JDK 5.0, Java provides a more powerful thread synchronization mechanism -- synchronization is achieved by explicitly defining synchronization Lock objects. Synchronous locks use Lock objects as.
l java.util.concurrent.locks.Lock interface is a tool that controls multiple threads to access shared resources. Locks provide exclusive access to shared resources. Only one thread can lock the lock object at a time. Threads should obtain the lock object before accessing shared resources.
The semantics of reentrant Lock is the same as that of reentrant Lock. It can realize the concurrency control of reentrant Lock and reentrant Lock.
9. Comparison between synchronized and Lock
\1. Lock is an explicit lock (manually open and close the lock, don't forget to close the lock), and synchronized is an implicit lock, which is automatically released out of the scope
\2. Lock only has code block lock, and synchronized has code block lock and method lock
\3. Using Lock lock, the JVM will spend less time scheduling threads and perform better. And it has better scalability (providing more subclasses)
Priority:
Lock - > synchronization code block (has entered the method body and allocated corresponding resources) - > synchronization method (outside the method body)
8-5 thread communication
wait() and notify() and notifyAll()
Ø wait(): make the current thread suspend and give up CPU, synchronize resources and wait, so that other threads can access and modify shared resources. While the current thread queues for other threads to call notify() or notifyAll() method to wake up. After waking up, it can continue to execute after regaining ownership of the monitor.
Ø notify(): wake up the thread with the highest priority waiting for synchronization resources and end the wait
Ø notifyAll(): wakes up all threads waiting for resources and ends waiting
l these three methods can only be used in synchronized methods or synchronized code blocks, otherwise they will report Java Lang.illegalmonitorstateexception exception.
l because these three methods must be called by a lock Object, and any Object can be used as a synchronized lock, these three methods can only be declared in the Object class.
wait() method
Call the method in the current thread: object name. wait()
Make the current thread enter the state of waiting (an object) until another thread issues notify (or notifyAll) to the object.
Necessary condition for calling method: the current thread must have the right to monitor (lock) the object
After calling this method, the current thread will release the object monitoring right and then enter the wait
After the current thread is notified, you need to regain the monitoring right, and then continue the execution of the code from the breakpoint.
notify(),notifyAll()
Call the method in the current thread: object name. notify()
Function: wake up a thread waiting for the monitoring right of the object.
Necessary condition for calling method: the current thread must have the right to monitor (lock) the object
8-6 JDK5.0 new thread creation method
New method 1: implement Callable interface
l compared with Runnable, Callable is more powerful
Ø compared with the run() method, it can have a return value
Ø method can throw exceptions
Ø return values that support generics
Ø you need to use the FutureTask class to get the returned results, for example
l Future interface
Ø you can cancel the execution results of specific Runnable and Callable tasks, query whether they are completed, obtain results, etc.
Ø FutrueTask is the only implementation class of Futrue interface
Ø FutureTask also implements Runnable and Future interfaces. It can be executed by the thread as Runnable or get the return value of Callable as Future
New method 2: use thread pool
Thread pool related API
9, Common Java classes
9-1 string related classes
Properties of String
1. Character string
2.String usage trap
3.String common methods
4.String and basic data type conversion
5.String and character array conversion
6. Conversion between string and byte array
7.StringBuffer class
Many methods are the same as String, but StingBuffer is of variable length. StringBuffer is a container.
StringBuffer Class is different from String,Its object must be generated by constructor. There are three construction methods (constructor): 1.StringBuffer()String buffer with initial capacity of 16 2.StringBuffer(int size)Constructs a string buffer of the specified capacity 3.StringBuffer(String str)Initializes the content to the specified string content String s = new String("I like learning"); StringBuffer buffer = new StringBuffer("I like learning "); buffer.append("mathematics");
Common methods of StringBuffer class
8.StringBuilder class
9-2 date and time API before jdk8
1.java.lang.System class
The public static long currentTimeMillis() provided by the System class is used to return the time difference in milliseconds between the current time and 0:0:0 on January 1, 1970.
Ø this method is suitable for calculating the time difference.
The main criteria for calculating world time are:
Ø UTC(Universal Time Coordinated)
Ø GMT(Greenwich Mean Time)
Ø CST(Central Standard Time)
2.java.util.Date class
Represents a specific moment, accurate to milliseconds
Construction method:
Ø Date() the object created by using the parameterless constructor of the Date class can obtain the local current time.
Ø Date(long date)
common method
Ø getTime(): returns the number of milliseconds represented by this Date object since 00:00:00 GMT, January 1, 1970.
Ø toString(): convert this Date object to the following String: dow mon dd hh:mm:ss zzz yyyy, where: dow is a day of the week (Sun, Mon, Tue, Wed, Thu, Fri, Sat), and zzz is the time standard.
Many other methods are outdated.
3. java.text.SimpleDateFormat class
Date date = new Date(); //Generate a Date instance //Generate an instance of formater formatting SimpleDateFormat formater = new SimpleDateFormat(); System.out.println(formater.format(date));//Default format for printouts SimpleDateFormat formater2 = new SimpleDateFormat("yyyy year MM month dd day EEE HH:mm:ss"); System.out.println(formater2.format(date)); //Instantiate a specified format object //Output in the specified format try { Date date2 = formater2.parse("2008 Monday, August 8, 2008:08:08"); //Parses the specified date and outputs it in the specified format System.out.println(date2.toString()); } catch (ParseException e) { e.printStackTrace(); }
Output is:
22-2-1 3 pm:03 2022 Tuesday, February 1, 2015:03:37 Fri Aug 08 08:08:08 CST 2008
4. java. util. Calendar Class
Calendar calendar = Calendar.getInstance(); // Get the Date object from a Calendar object Date date = calendar.getTime(); //Set the time of this Calendar with the given Date calendar.setTime(date); calendar.set(Calendar.DAY_OF_MONTH, 8); System.out.println("The current time day is set to 8 days later,Time is:" + calendar.getTime()); calendar.add(Calendar.HOUR, 2); System.out.println("Current time plus 2 hours,Time is:" + calendar.getTime()); calendar.add(Calendar.MONTH, -2); System.out.println("Current date minus 2 months,Time is:" + calendar.getTime());
Output is:
The current time day is set to 8 days later,Time is:Tue Feb 08 15:06:01 CST 2022 Current time plus 2 hours,Time is:Tue Feb 08 17:06:01 CST 2022 Current date minus 2 months,Time is:Wed Dec 08 17:06:01 CST 2021
9-3 new date and time API in jdk8
l Java 8 absorbs the essence of Joda-Time and creates a good API for Java at a new beginning. New Java Time contains all classes about local Date, local time, local datetime, ZonedDateTime, and Duration. The long-standing Date class adds a toinst () method to convert Date into a new representation. These new localized time and Date APIs greatly simplify the management of Date and time and localization.
New date API
java.time – the base package that contains the value object
java.time.chrono – provides access to different calendar systems
java.time.format – format and parse time and date
java. time. Temporary – includes the underlying framework and extension features
java.time.zone – contains classes supported by time zones
Note: most developers only use the basic package and format package, and may also use the temporary package. Therefore, although there are 68 new public types, most developers will use only about one-third of them.
1.LocalDate,LocalTime,LocalDateTime
l LocalDate, LocalTime and LocalDateTime are the more important classes. Their instances are immutable objects, which respectively represent the date, time, date and time using the ISO-8601 calendar system. They provide a simple local date or time and do not contain current time information or time zone related information.
Ø LocalDate represents the date in IOS format (yyyy MM DD), which can store birthday, anniversary and other dates.
Ø LocalTime represents a time, not a date.
Ø LocalDateTime is used to represent date and time, which is one of the most commonly used classes.
Note: ISO-8601 calendar system is the representation of the date and time of modern citizens formulated by the international organization for standardization, that is, the Gregorian calendar.
2. Instantaneous: Instant
3. Format and parse date or time
4. Other API s
5. Conversion with traditional date processing
9-4 Java comparator
l in Java, the sorting of object arrays is often involved, so it involves the comparison between objects.
L there are two ways to sort objects in Java:
Natural sorting: Java lang.Comparable
Customized sorting: Java util. Comparator
Method 1: natural sorting: Java lang.Comparable
Method 2: custom sorting: Java util. Comparator
9-5 System class
l System class represents the system. Many system level attributes and control methods are placed inside this class. This class is located in Java Lang package.
l since the constructor of this class is private, the object of this class cannot be created, that is, the class cannot be instantiated. Its internal member variables and member methods are static, so they can also be called conveniently.
l member variables
The Ø System class contains three member variables: in, out and err, which represent standard input stream (keyboard input), standard output stream (display) and standard error output stream (display) respectively.
l member method
Ø native long currentTimeMillis():
The function of this method is to return the current computer time. The expression format of time is the millisecond difference between the current computer time and GMT (Greenwich mean time) on January 1, 1970.
Ø void exit(int status):
The function of this method is to exit the program. Where the value of status is 0, which represents normal exit, and non-zero represents abnormal exit. Using this method, the exit function of the program can be realized in the graphical interface programming.
Ø void gc():
The function of this method is to request the system for garbage collection. As for whether the system recycles immediately, it depends on the implementation of the garbage collection algorithm in the system and the execution of the system.
Ø String getProperty(String key):
This method is used to obtain the value corresponding to the attribute named key in the system. The common attribute names and functions in the system are shown in the following table:
9-6 Math class
java.lang.Math provides a series of static methods for scientific calculation; The parameter and return value types of the method are generally double.
abs absolute value acos,asin,atan,cos,sin,tan trigonometric function sqrt square root pow(double a,doble b) a of b pow log Natural logarithm exp e Bottom index max(double a,double b) min(double a,double b) random() Return 0.0 To 1.0 Random number of long round(double a) double Type data a Convert to long Type (rounded) toDegrees(double angrad) Radian ->angle toRadians(double angdeg) Angle ->radian
9-7 BigInteger and BigDecimal
1.BigInteger class
common method
2.BigDecimal class
10, Enumeration classes and annotations
10-1 use of enumeration classes
l implementation of enumeration class
Ø JDK1. You need to customize the enumeration class before 5
The enum keyword added in JDK 1.5 is used to define enumeration classes
l if the enumeration has only one object, it can be used as an implementation of singleton mode.
l enumeration class properties
The properties of enumeration class objects should not be allowed to be changed, so they should be decorated with private final
The attribute of enumeration class decorated with private final should be assigned a value in the constructor
Ø if the enumeration class explicitly defines a constructor with parameters, the corresponding incoming parameters must also be used when listing the enumeration values
1. User defined enumeration class
2. Use enum to define enumeration class
Main methods of enumerating classes
L main methods of enum class:
Ø * * values() * * method: returns an array of objects of enumeration type. This method can easily traverse all enumerated values.
Ø valueOf(String str): you can convert a string into a corresponding enumeration object. The required string must be the name of an enumeration class object. If not, there will be a runtime exception: IllegalArgumentException.
Ø toString(): returns the name of the object constant of the current enumeration class
Enumeration class that implements the interface
l like ordinary Java classes, enumeration classes can implement one or more interfaces
l if each enumeration value presents the same behavior when calling the interface method implemented, it is only necessary to implement the method uniformly.
l if you need each enumeration value to show different behavior when calling the interface method implemented, you can let each enumeration value implement the method separately
10-2 annotation
l since JDK 5.0, Java has added support for metadata, that is, annotation
l Annotation is actually a special mark in the code. These marks can be read during compilation, class loading and runtime, and the corresponding processing can be executed. By using Annotation, programmers can embed some supplementary information in the source file without changing the original logic. Code analysis tools, development tools and deployment tools can be verified or deployed through these supplementary information.
l Annotation can be used as a modifier to modify the declaration of packages, classes, constructors, methods, member variables, parameters and local variables. This information is saved in the name=value pair of Annotation
l Annotation can be used to set metadata for program elements (classes, methods, member variables, etc.)
l in Java se, annotations are used for simple purposes, such as marking outdated functions, ignoring warnings, etc. Annotations play a more important role in Java EE / Android, such as configuring any aspect of the application, replacing the cumbersome code and XML configuration left over from the old version of Java EE.
l future development models are annotation based, JPA is annotation based, spring 2 5 the above are based on annotations, hibernate 3 X will also be based on annotation in the future. Now some of struts 2 is also based on annotation. Annotation is a trend. To a certain extent, it can be said: Framework = annotation + reflection + design pattern.
1. Common Annotation examples
2. Example 2: format check during compilation (three basic annotations built into JDK)
Ø @ Override: restrict overriding parent class methods. This annotation can only be used for methods
Ø @ Deprecated: used to indicate that the modified element (class, method, etc.) is obsolete. Usually because the modified structure is dangerous or there is a better choice
Ø @ SuppressWarnings: suppress compiler warnings
3. Example 3: track code dependency and realize the function of replacing configuration file
Ø Servlet3.0 provides annotation, so that it is no longer needed on the web Deploy servlets in XML files.
Transaction management in spring framework
4. User defined Annotation
5. Meta annotation in JDK
L the meta Annotation of JDK is used to modify other Annotation definitions
l JDK5.0 provides four standard meta annotation types:
ØRetention
ØTarget
ØDocumented
ØInherited
Understanding of metadata: String name = "atguigu";
@Retention
@Target
@Documented
@Inherited
6. Use reflection to obtain annotation information
7. New features of annotations in jdk8
If you like, please pay attention to me
So far, our java learning (middle) has been explained. In the next section, we will introduce generics, IO flow, network programming, reflection mechanism, Java8, 9, 10, 11 new features and common interview questions. Like I can pay attention to my WeChat official account, I love learning, hee hee, and share all kinds of resources from time to time.
Java learning (Part 1): overview of Java, basic syntax, array