Concept of method and encapsulation
######Basic concepts of construction method------------------------------class Class name{ Class name(parameter list ){ Construction method body; } } //as class Person{ Person(){ //Constructor in Person class } }
The constructor name is exactly the same as the class name, and there is no return value type, not even void
Default constructor: when no constructor is defined in a class, the compiler will automatically add a parameterless null constructor, that is, a parameterless constructor
It is called default / default construction method, such as:
Person(){};
If a constructor occurs in a class, the compiler no longer provides any form of constructor
The advantage of constructor is that you can operate your own member variables in the constructor, but the default constructor does not have such operations
Function of constructor: when creating an object with the new keyword, the constructor will be called automatically to initialize member variables
/* Programming the definition of person class */ public class Personn{ String name; //Member variable describing the name int age; //Member variables used to describe age //Custom construction method /* Personn(){ // System.out.println("I am the custom construction method! "); //name = "Zhang Fei "; //age = 30; } */ Personn(String s,int i){ name = s; age = i; } void show(){ //Increase the age by one year whenever you print the value of the member variable this.grow(); //this. The prefix can be removed System.out.println("I am" + name + ",this year" + age + "Years old!"); } //The custom member method implements the behavior of increasing the age by one year void grow(){ age++; } //The custom member method implements the behavior of the value specified by the age growth parameter void grow(int i){ age += i; } //The custom member method implements the behavior of obtaining and returning the object of person type Personn getPersonn(){ //Returns the current calling object itself Person TP = new Person (); return tp; return this; } public static void main(String[] args){ //Declare a reference of type person to an object of type person //When the constructor is not provided in the class, the default constructor will be called below. If the constructor is provided in the class, the version provided in the class will be called below Personn p1 = new Personn("Fei Zhang",30); //Parameterless call parameterless construction method, parameterless call parameterless construction method //And print features p1.show(); //null 0 Zhang Fei 30 Personn p2 = new Personn("Guan Yu",40); p2.show(); //Guan Yu 35 //Personn p3 = new Personn(); // Error: cannot apply constructor person in class person to the given type; //Because there is a constructor, the compiler will not automatically add the default parameterless constructor. Therefore, if it fails to call the constructor, it will report an error //p3.show(); System.out.println("--------------------------------------------------------------------"); p2.grow(); p2.show();//Guan Yu 36 p2.grow(2); p2.show();//Guan Yu 38 System.out.println("--------------------------------------------------------------------"); //Call the member method to get the object Personn pp = p1.getPersonn(); System.out.println("p1 = " + p1); System.out.println("pp = " + pp); pp.show(); } }
Case title------------------------------
Programmatically implement the definition of Pointt class and add construction methods to Pointt class
Pointt() creates the origin object by default
Pointt(int i,int j) creates a point object based on parameters
/* Programming the definition of Pointt class */ public class Pointt{ int x; //Member variable used to express abscissa int y; //Member variables used to express ordinates //Custom parameterless construction method Pointt(){ } //Custom parametric construction method Pointt(int i,int j){ x = i; y = j; } //Custom member method to print features void show(){ System.out.println("Abscissa is:" + x + ",The ordinate is:" + y); } void up(){ y--; } void up(int dy){ y -= dy; } public static void main(String[] args){ //Construct objects and plot features in a parameterless manner Pointt p1 = new Pointt(); p1.show(); //Use parametric methods to construct objects and plot features Pointt p2 = new Pointt(3,5); p2.show(); System.out.println("--------------------------------------------------------------------"); p2.up(); p2.show(); //3 4 p2.up(2); p2.show(); //3 2 } }
Concept and embodiment of overload------------------------------
If the method names are the same and the parameter lists are different, such methods form an Overload relationship
The main forms of method overloading are: different number of parameters, different types of parameters, different order of parameters, independent of the return value type and formal parameter variable name
However, it is recommended that the return value types should be the same, because if they are different, we need to deal with the return value. If they are the same, we don't need to deal with them very troublesome
Judge whether methods can form the core of overloading: whether they can be distinguished when calling methods
Exercise topic------------------------------
Programming Pointt class to add overloaded member methods
up() realizes the function of subtracting 1 from the ordinate
up(int dy) realizes the function of subtracting the specified value of the parameter from the ordinate
Call rules for testing overloaded methods
/* Programming the definition of Pointt class */ public class Pointt{ int x; //Member variable used to express abscissa int y; //Member variables used to express ordinates //Custom parameterless construction method Pointt(){ } //Custom parametric construction method Pointt(int i,int j){ x = i; y = j; } //Custom member method to print features void show(){ System.out.println("Abscissa is:" + x + ",The ordinate is:" + y); } void up(){ y--; } void up(int dy){ y -= dy; } public static void main(String[] args){ //Construct objects and plot features in a parameterless manner Pointt p1 = new Pointt(); p1.show(); //Use parametric methods to construct objects and plot features Pointt p2 = new Pointt(3,5); p2.show(); System.out.println("--------------------------------------------------------------------"); p2.up(); p2.show(); //3 4 p2.up(2); p2.show(); //3 2 } }
Practical significance of overloading------------------------------
The practical significance of method overloading is that the caller only needs to remember a method name to call different versions to achieve different functions
For example: Java io. println method in printstream class
Similar to the operation when printing variables, variables can be of many types, which are overloaded, such as system out. println()
/* Test of main forms of programming method overload */ public class OverloadTest{ //Custom member method void show(){ System.out.println("show()"); } void show(int i){ //ok is reflected in the different number of method parameters System.out.println("show(int)"); } void show(int i,double d){ //ok is reflected in the different number of method parameters System.out.println("show(int,double)"); } void show(int i,int j){ //ok is reflected in the different types of method parameters System.out.println("show(int,int)"); } void show(double i,int j){ //ok is reflected in the different order of method parameters System.out.println("show(double,int)"); } /* void show(double a,int b){ //error(Error) independent of the variable name of the parameter System.out.println("show(double,int)"); } */ /* int show(double a,int b){ //error(Error) independent of return value type System.out.println("show(double,int)"); } */ //In the above two irrelevant, if used, it will point to two methods, that is, if you don't know which of the two methods to call, an error will be reported //That is, there must be only one method left, so there will be no error public static void main(String[] args){ //Declare that a reference to the overload text type points to an object of that type OverloadTest ot = new OverloadTest(); //Call the show method (); ot.show(); ot.show(66); ot.show(66,3.14); ot.show(66,3); ot.show(3.14,66); //ot.show(3.14,66); } }
Basic concept of this------------------------------
If this keyword appears in the construction method, it represents the object currently being constructed
If this keyword appears in the member method, it represents the object currently being called
this keyword is essentially a reference variable of the current class type
//When there is in the method System.out.println("I am" + name + ",this year" + age + "Years old!"); //name and age imply this keyword, that is, this name and this age //For example, Person this = p1; this.name = p1.name = Zhang Fei //Person this = p2; this.name = p2.name = Guan Yu
How the this keyword works------------------------------
When accessing member variables in constructor and member methods, the compiler adds this Prefix of
And this It is equivalent to "my" in Chinese. When different objects call the same method, the this keyword is different due to different objects calling the method
So this The results of access are also different
How this is used------------------------------
//If there are the following codes public class test{ int i; String s; //Just in principle lazy principle when the member variable name has the same name as the formal parameter variable name, whoever is closer will be assigned the value test(int i,String s){ //i = i; i are all parameter variable names //s = s; s are all formal parameter variable names this.i = i; //In this way, you can make the member variable on the left this.s = s; //Such an operation can know the name of the formal parameter variable and the service member variable //It's basically written like this in the future } }
When the local variable name is the same as the member variable name, the local variable will be used preferentially in the method body (proximity principle)
If you want to use a member variable, you need to precede the member variable with this Prefix, which clearly requires that the variable is a member variable (top priority)
This keyword can be used in addition to this In addition to calling member variables and member methods, it can also be used as the return value of the method (focus)
In the first line of the construction method, you can call other construction methods in this class through this() (understand)
As for why it must be the first line, because if it is not the first line, we will operate on some things of the class, such as member variables
After the operation, if the constructor is called again with this, the operation will be repeated, that is, only the first line can be specified
/* Programming the use of this keyword */ public class ThisTest { //Custom construction method ThisTest(){ //this represents the object currently being constructed// System.out.println("In the construction method: this = " + this); } //Custom member method void show(){ //this represents the object currently being called System.out.println("In the member method: this = " +this); } public static void main(String[] args) { //A reference declaring the ThisTest type points to an object of that type ThisTest tt = new ThisTest(); //Call the show() method tt.show(); System.out.println("main Method: tt = " + tt); } }
Note: this is only available during execution, that is, whoever executes it represents who. For example, a.fa() represents a, and new aa() represents his address
/* Programming the definition of Boy class */ public class Boy { String name; //Member variable describing the name //Custom construction method Boy(){ //Call the parameterized constructor in this class //this(); Error: recursive constructor call cannot repeat itself //this("Zhang Fei"); System.out.println("Nonparametric construction method"); } Boy(String name){ this(); //When using a constructor again, if a constructor is called, an error will be reported if the called constructor can come back //If this() has this (1) in this() and this() in this (1), there will be an infinite loop, that is, an error will be reported System.out.println("-------Parametric construction method"); this.name = name; } //Custom member method to print features void show(){ System.out.println("My name is:" + name); } public static void main(String[] args) { //Construct objects and plot features in a parameterless manner Boy b1 = new Boy(); b1.show(); //null System.out.println("--------------------------------------------------------------------"); //Use parametric methods to construct objects and plot features Boy b2 = new Boy("Fei Zhang"); b2.show(); //Fei Zhang } }
Precautions------------------------------
The reference type variable is used to store the address of the object. You can assign null to the reference type, indicating that it does not point to any object
When a reference type variable is null, the object cannot be accessed (because it does not point to any object)
At this time, if you access a member variable or call a method by reference, a NullPointerException exception will be generated
Case title------------------------------
The factorial of parameter n is programmed and returned. The so-called factorial is the result of cumulative multiplication from 1 to n
/* The calculation and printing of cumulative product are realized by programming */ public class JieChengTest{ //The custom member method calculates the factorial of parameter n and returns it // 1! = 1; 2! = 2; 3! = 6; ... n! = 1*2*3*...*n; int show(int n){ //int 5 //Recurrence /* int num = 1; for(int i = 1;i<=n;i++){ num *= i; } return num; */ /* 5!= 5*4*3*2*1; 4! = 4*3*2*1; 3! = 3*2*1; 2! = 2*1; 1! = 1; 5! = 5 * 4!; 4! = 4 * 3!; 3! = 3 * 2!; 2! = 2 * 1!; 1! = 1; n! = n * (n-1)!; */ //Recursive way //When the value of n is 1, the result of factorial is 1 /* if(1 == n){ return 1; } */ if(1 == n) return 1; //Otherwise, the result of factorial is n*(n-1) return n * show(n-1); //show(5) => return 5*show(4); =>120 //show(4) => return 4*show(3); =>24 //show(3) => return 3*show(2); =>6 //show(2) => return 2*show(1); =>2 //show(1) => return 1; => 1 } public static void main(String[] args) { //A reference declaring the JieChengTest type points to an object of that type JieChengTest jct = new JieChengTest(); //Call the method to calculate and print int res = jct.show(5); System.out.println("The final calculation result is:" + res); } }
Basic concepts of recursion------------------------------
The essence of recursion is to call the current method itself directly or indirectly inside the method body
The use of recursion must have the law of recursion and exit conditions
Using recursion must simplify the problem rather than complicate it
If recursion affects the execution performance of the program, recursion is used instead
Case title------------------------------
The value of the nth item in the fee series is programmed and returned
Fee series: 1 1 2 3 5 8 13 21
/* The calculation and printing of fee series are realized by programming */ public class FeeTest{ //The user-defined member method calculates and returns the value of the nth item in the fee array. n is specified by the parameter // 1 1 2 3 5 8 13 21 .... int show(int n){ // int n = 5 /* //The calculation is performed recursively //When n=1 or n=2, the result is 1 if(1 == n || 2 == n){ return 1; } //Otherwise, the result is the sum of the first two items return show(n-1) + show(n-2); //show(5) => return show(4) + show(3); =>5 //show(4) => return show(3) + show(2); =>3 //show(3) => return show(2) + show(1); =>2 //show(2) => return 1; =>1 //show(1) => return 1; =>1 */ //The calculation is carried out in a recursive manner int ia = 1; int ib = 1; for(int i= 3; i<=n; i++){ int ic = ia + ib; ia = ib; ib = ic; } return ib; } public static void main(String[] args) { //A reference declaring a FeeTest type points to an object of that type FeeTest ft = new FeeTest(); //Call the method to calculate and print int res = ft.show(5); System.out.println("The end result is:" + res); // 5 } }
Split the above code
/* Programming the calculation and printing function class of fee series */ public class Fee{ //The user-defined member method calculates and returns the value of the nth item in the fee array. n is specified by the parameter // 1 1 2 3 5 8 13 21 .... int show(int n){ // int n = 5 /* //The calculation is performed recursively //When n=1 or n=2, the result is 1 if(1 == n || 2 == n){ return 1; } //Otherwise, the result is the sum of the first two items return show(n-1) + show(n-2); //show(5) => return show(4) + show(3); =>5 //show(4) => return show(3) + show(2); =>3 //show(3) => return show(2) + show(1); =>2 //show(2) => return 1; =>1 //show(1) => return 1; =>1 */ //The calculation is carried out in a recursive manner int ia = 1; int ib = 1; for(int i= 3; i<=n; i++){ int ic = ia + ib; ia = ib; ib = ic; } return ib; } }
/* Programming the test class of fee series class */ public class FeeTest{ public static void main(String[] args) { //A reference declaring a Fee type points to an object of that type Fee ft = new Fee(); //Call the method to calculate and print int res = ft.show(5); System.out.println("The end result is:" + res); // 5 } }
The above can be called separately. While compiling the FeeTest class, the feeclass of the main method will also be compiled. Finally, the corresponding results can be obtained by executing the FeeTest class
But you can't directly use Java feetest Java runs, because it can only operate on this class, that is, the class of Fee is not recognized, so it needs to be compiled and run
And use Java feetest Java, you can do it in one step (compile and execute together)
He will check whether you have compiled it first. If you have compiled it, an error will be reported, because he must be in place in one step and there must be no place where he has already operated
However, if your Fee class is compiled and recognized, the Java feetest Java is one-step, so it will also report an error
It can be seen from the above that recursion needs to be executed many times, which will affect the performance, that is, using recursion
Concept of encapsulation------------------------------
In general, you can assign some legal but unreasonable values to member variables in the test class, and there will be no error or prompt in either the compilation stage or the run stage
This is not in line with real life
In order to avoid the above errors, member variables need to be sealed and packaged
To hide the details of member variables and ensure the rationality of member variable values, this mechanism is called encapsulation
Implementation process of encapsulation------------------------------
Privatize member variables and use the private keyword to modify them
Provide public get and set methods, and judge the reasonable value in the method body
In the construction method, we call the set method to judge the reasonable value.
/* Programming to realize the encapsulation of Student class */ public class Student{ //Privatize member variables and use the private keyword to modify them //Private keyword modification means private, that is, the member variable can only be used inside the current class private int id; //Member variable used to describe student number private String name; //Member variable describing the name public Student(){ } //In the public construction method, we call the set method to judge the reasonable value. public Student(int id,String name){ //this.id = id; //this.name = name; setId(id); setName(name); } //Provide public get and set methods, and judge the reasonable value in the method body //Use the public keyword to modify the meaning of public, that is, the method can be used anywhere public int getId(){ return id; } public void setId(int id){ if(id > 0){ this.id = id; }else{ System.out.println(id + "The student number is unreasonable"); } } public String getName(){ return name; } public void setName(String name){ this.name = name; } //Custom member method to print features //There is no default access permission for any modifier, and the level is between private and public void show(){ //System.out.println("I am:" + name + ", my student number is:" + ID "); System.out.println("I am:" + getName() + ",My student number is:" + getId()); //This method is more maintainable } }
/* Test of Student class by programming */ public class StudentTest{ public static void main(String[] args) { //A reference declaring Student type points to an object of Student type Student s1 = new Student(); //Assign and print member variables //s1.id = 100; //s1.name = "Zhang Fei"; s1.setId(100); s1.setName("Fei Zhang"); s1.show(); System.out.println("--------------------------------------------------------------------"); //s1.id = -1100; //s1.name = "Zhang Fei"; s1.setId(-1100); s1.setName("Fei Zhang"); s1.show(); System.out.println("--------------------------------------------------------------------"); //Use parametric methods to construct objects and plot features Student s2 = new Student(-1001,"Guan Yu"); s2.show(); } }
Case title------------------------------
Prompt the user to input the number of students in the class to follow the information of each student. The student information includes: student number and name, and finally print them out separately
Prompt: Student[] arr = new Student[num];
/* Programming realizes the input and printing of student information */ import java.util.Scanner; public class StudentTest2 { public static void main(String[] args) { // 1. Prompt the user to enter the number of students and use variable records System.out.println("Please enter the number of students:"); Scanner sc = new Scanner(System.in); int num = sc.nextInt(); // 2. Prepare the corresponding one-dimensional array according to the number of students // int[] arr = new int[3]; - Represents declaring a one-dimensional array with a length of 3 and an element type of int // Every element in the array is of type int, that is, every element in the array can be regarded as a variable of type int //Use integer data for initialization. arr[0] = 10; // The following code is to declare a one-dimensional array with length of num and element type of Student // Each element in the array is of Student type, that is, each element in the array can be regarded as a variable of Student type //arr[0] = new Student(); Student[] arr = new Student[num]; // 3. Prompt the user to input the information (student number and name) of each student and record it in the one-dimensional array for(int i = 0; i < num; i++) { System.out.println("Please enter page" + (i+1) + "Student information(Student ID name): "); arr[i] = new Student(sc.nextInt(), sc.next()); } System.out.println("-----------------------------------------------"); // 4. Print all student information System.out.println("All student information in this class includes:"); for(int i = 0; i < num; i++) { //System.out.println(arr[i]); arr[i].show(); } } }
Concept of JavaBean------------------------------
JavaBeans are reusable components written in Java language. Other Java classes can discover and manipulate the properties of these JavaBeans through reflection mechanism
JavaBean s are essentially Java classes that meet the following standards
Class is public
There is a public constructor without parameters
There are properties and corresponding get and set methods
Summary------------------------------
Construction method (top priority)
Syntax format, default construction method, initialization of member variables
Method overload (key)
Concept, embodiment and practical significance
this keyword (principle)
Concept, principle and usage
Recursion (difficulty)
Concept and principle of use
Packaging (top priority)
ystem.out.println("please enter" + (i+1) + "student information (student number name):");
arr[i] = new Student(sc.nextInt(), sc.next());
}
System.out.println("-----------------------------------------------"); // 4. Print all student information System.out.println("All student information in this class includes:"); for(int i = 0; i < num; i++) { //System.out.println(arr[i]); arr[i].show(); } }
}
###### Concept of JavaBean------------------------------ ###### JavaBeans are reusable components written in Java language. Other Java classes can discover and manipulate the properties of these JavaBeans through reflection mechanism ###### JavaBean s are essentially Java classes that meet the following standards ###### Class is public ###### There is a public constructor without parameters ###### There are properties and corresponding get and set methods ###### Summary------------------------------ ###### Construction method (top priority) ###### Syntax format, default construction method, initialization of member variables ###### Method overload (key) ###### Concept, embodiment and practical significance ###### this keyword (principle) ###### Concept, principle and usage ###### Recursion (difficulty) ###### Concept and principle of use ###### Packaging (top priority) ###### Concept and implementation process