This is the 14th day of my participation in the August Text Challenge.More challenges in August

1. Process oriented and object oriented

What is the idea of “object-oriented” programming? First, explain “thought”. Let me ask you a question: what do you want to be? Maybe you will answer: I want to be a good person, filial piety parents, respect elders, care for relatives… You see, this is the mind. These are your ideas, or your principles. There are principles of being a man, and there are principles of programming. These principles of programming are ideas of programming.

Procedural (POP) vs. Object-oriented (OOP)

  • Object Oriented: Object Oriented Programming
  • Procedure Oriented Programming
Java classes and their members: properties, methods, constructors, code blocks, inner classes * 2. Three characteristics of object orientation: encapsulation, inheritance, polymorphism, (abstractness) * 3. This, super, static, final, abstract, interface, package, import, etc. Process-oriented: Emphasizes functional behavior, takes function as the smallest unit, and considers how to do it. * * ① Open the refrigerator * ② put the elephant in the refrigerator * ③ Close the refrigerator door * * 2. Object orientation: Emphasize objects with functionality, class/object as the smallest unit, and consider who does it. * people {* open (refrigerator){* refrigerator. Open the door (); *} Operation (elephant){* Elephant. To enter (a refrigerator); *} Close (refrigerator){* refrigerator. Close (); * * * *}} {* refrigerator door closed () ()} {* *}} {* * * * the elephant into the (refrigerator) {x} {* *} * /
Copy the code

An overview of object-oriented thinking

  • Programmers are transformed from process-oriented performers to object-oriented leaders
  • The ideas and steps of object-oriented analysis method:
    • Based on the needs of the problem, select the real-world entities that the problem addresses.
    • Look for properties and functions related to solving problems in entities, and these properties 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 some programming language, the class is constructed into a computer can recognize and process the data structure.
    • Instantiate classes into objects in the computer world. Objects are the ultimate problem-solving tool in the computer world.

2. Classes and objects

Class: a description of a class of things, which is an abstract, conceptual definition. * Object: each individual of the class of things that actually exists, thus also called an instance. * Can be understood as: class = abstract concept of people; Object = real someone * Object oriented programming focuses on the design of classes; * A design class is a member of a design class. * /
Copy the code

2.1. Java classes and class members

Real-world organisms, from whales to ants, are made up of the most basic cells. Similarly, the Java code world is made up of many classes with different functions.

What are cells made of in the real biological world? Nucleus, cytoplasm,… So, too, is Java’s use of classes to describe things. Common class members are:

  • Attribute: A member variable in the corresponding class
  • Behavior: member methods in the corresponding class

2.2 Creation and use of classes and objects

Field = member variables = fields * Method = (member) methods = functions * * Create class = instantiate class = instantiate class * * 2 Use of classes and objects (implementation of object-oriented thinking) * 1. Create classes and design members of classes * 2. Create an object of class * 3. Properties or objects. 3. If you create multiple objects of a class, each object has its own set of class attributes. (non-static) * means that if we modify the property a of one object, the value of the property A of the other object is not affected. * /
/ / test class
public class PersonTest {
	public static void main(String[] args) {
		//2. Create an object of the Person class
		// Create object syntax: class name object name = new class name ();
		Person p1 = new Person();
		//Scanner scan = new Scanner(System.in);
		
		// Call the class structure: attributes, methods
		// Invoke property: "object. Attribute"
		p1.name = "Tom";
		p1.age = 25;
		p1.isMale = true;
		System.out.println(p1.name);
		
		// Call the method: "object. Methods"
		p1.eat();
		p1.sleep();
		p1.talk("chinese");
		/ / * * * * * * * * * * * * * * * * * * * * * *
		Person p2 = new Person();
		System.out.println(p2.name); //null
		System.out.println(p2.isMale);
		/ / * * * * * * * * * * * * * * * * * * * * * *
		// assign p1 and P3 to an object entity in heap space.
		Person p3 = p1;
		System.out.println(p3.name);
		
		p3.age = 10;
		System.out.println(p1.age); / / 10}}/* * class syntax: * modifier class name {* attribute declaration; * Method declaration; *} * The modifier public: the class can be accessed arbitrarily. The body of the class is enclosed in {} */
//1. Create a class and design its members
class Person{
	
	// Attribute: a member variable in the corresponding class
	String name;
	int age;
	boolean isMale;
	
	// method: a member method of the corresponding class
	public void eat(a){
		System.out.println("Eat");
	}
	
	public void sleep(a){
		System.out.println("Sleep");
	}
	
	public void talk(String language){
		System.out.println("People can speak, using:"+ language); }}Copy the code

2.3 Object creation and use: memory parsing

  • An area of memory whose sole purpose is to hold object instances, where almost all object instances are allocated memory. This is described in the Java Virtual Machine specification: all object instances and arrays are allocated on the heap.
  • Usually referred to as the Stack (Stack), refers to the virtual machine Stack. The virtual machine stack is used to store local variables and so on. The local variable table holds various basic data types (Boolean, byte, CHAR, short, int, float, long, double) and object references (the reference type, which is not the same as the object itself, but is the first address of the object in the heap memory) that are known at compile time. Method is automatically released after execution.
  • MethodArea, which stores information about classes that have been loaded by the virtual machine, constants, static variables, code compiled by the just-in-time compiler, and so on.

1. Case 1

Person p1= newPerson();
p1.name = "Tom";
p1.isMale = true;
Person p2 = new Person();
sysout(p2.name);//null
Person p3 = p1;
p3.age = 10;
Copy the code

2. Case 2

Person p1= newPerson();
p1.name = "Hu Limin";
p1.age = 23;
Person p2 = new Person();
p2.age = 10;
Copy the code

3. One of the members of a class: an attribute

/* * Class attributes use * * attributes (member variables) vs local variables * 1. Similarities: * 1.1 Format for defining variables: Data type Variable name = variable value * 1.2 Declared first, then used * 1.3 Variables have their corresponding scope * * 2. Difference: Attributes: local variables: variables declared in methods, method parameters, constructor parameters, and constructors * * 2.2 Differences about permission modifiers * Attributes: You can specify the permissions of attributes when declaring them, and use permission modifiers. * Common permission modifiers :private, public, default, protected * Currently, when declaring attributes, use the default. * Local variables: Permission modifiers cannot be used. * * attributes: Attributes of a class that, depending on their type, have default initialization values. * Int (byte, short, int, long):0 * Float (double):0.0 * Char (0) (or '\u0000') * Boolean (Boolean):false * * Reference data types (class, array, interface): NULL * * Local variables: No default initialization value * means that an explicit assignment must be made before a local variable is called. * Specifically: when a parameter is called, it is assigned. For example, line 45 * * 2.4 is loaded at different locations in memory. * Properties: loaded into heap space (non-static) * local variables: loaded into stack space */
public class UserTest {
	public static void main(String[] args) {
		User u1 = new User();
		System.out.println(u1.name);
		System.out.println(u1.age);
		System.out.println(u1.isMale);
		
		u1.talk("Russian"); }}class User{
	// Attribute (or member variable)
	String name;	// No private is the default
	public int age;	// No public is the default
	boolean isMale;
	
	public void talk(String language){//language: parameter, also a local variable
		System.out.println("We use" + language + "Communicate.");
	}
	
	public void eat(a){
		String food = "Stone cake";	// Stone cake: local variable
		System.out.println("Northerners like to eat :"+ food); }}Copy the code

1

/* Write the teacher class and the Student class, and test the Student class properties by creating objects from the test class: Name :String age:int major:String interests:String method :say() Name :String age:int teachAge:int course:String Method :say() Outputs the teacher's personal information */
public class School {
	public static void main(String[] args) {
		Student stu = new Student();
        stu.name = "Xiao Ming";
        stu.age = 16;
		
		Teacher tea = new Teacher();
		tea.name = "Miss Wang";
        tea.age = 27; tea.say(stu.name,stu.age); stu.say(tea.name, tea.age); }}class Student{
	String name;
	int age;
	String major;
	String interests;
	
	void say(String name, int age){
		System.out.println("This student is:"+name+"The age is:"+age); }}class Teacher{
	String name;
	int age;
	String teachAge;
	String course;
	
	void say(String name, int age){
		System.out.println("This teacher is:"+name+"The age is:"+age); }}Copy the code

The second member of the class is a method

4.1 declaration and use of methods in a class

/* * The declaration and use of * * methods in a class: describes what the class should do. * For example: Math class: SQRT ()\random() \... * Scanner class: nextXxx()... * Arrays class: sort() \ binarySearch() \ toString() \ equals() \... * * 1.  * public void eat(){} * public void sleep(int hour){} * public String getName(){} * public String getNation(String nation){} * * 2. Method declaration: Permission modifier return value type method name (parameter list){* Method body *} * Note: static, final, and abstract methods are modified later. * * 3. Description: * 3.1 About permission modifiers: the default method permission modifiers are public * Java provides four types of permission modifiers: private, public, default, protected --> encapsulation * * 3.2 Return value type: Return value vs No return value * 3.2.1 If a method has a return value, the type of the return value must be specified when the method is declared. Also, the * return keyword is used to return a variable or constant of the specified type: "return data". * If the method does not return a value, void is used when the method is declared. In general, there is no need for * to use return in methods that do not return a value. However, if it does, only "return;" can be used. To end this method. * * 3.2.2 Should we define methods that return values? * * 3.3 Method names: belong to identifiers and follow the rules and specifications of identifiers. * 3.4 Parameter list: A method name can have zero, one, or more parameters. * 3.4.1 Format: Data type 1 parameter 1, Data type 2 parameter 2... * * 3.4.2 When we define methods, should we define parameters? * ① Questions * ② By experience, specific problems specific analysis * 3.5 Method body: the embodiment of method function. * 4. Use of the return keyword: * 1. Use scope: use in the method body * 2. Job :① End method * ② For methods with return value type, use the "return data "method to return the desired data. * 3. Note that an execution statement cannot be declared after the return keyword. * 5. When using a method, you can call a property or method of the current class. * Special: method A also calls method A: recursive method. * No other methods can be defined in a method. * /
public class CustomerTest {
	public static void main(String[] args) {
		
		Customer cust1 = new Customer();
		
		cust1.eat();
		
		// Test whether the parameter needs to be set
// int[] arr = new int[]{3,4,5,2,5};
// cust1.sort();
		
		cust1.sleep(8); }}/ / the customer class
class Customer{
	
	/ / property
	String name;
	int age;
	boolean isMale;
	
	/ / method
	public void eat(a){
		System.out.println("Customers eat.");
		return;
		// An expression cannot be declared after return
// System.out.println("hello");
	}
	
	public void sleep(int hour){
		System.out.println("Rest." + hour + "Hours");
		
		eat();
// sleep(10);
	}
	
	public String getName(a){
		
		if(age > 18) {return name;
			
		}else{
			return "Tom"; }}public String getNation(String nation){
		String info = "My nationality is:" + nation;
		return info;
	}
	
	// See if parameters need to be set
//	public void sort(int[] arr){
//		
//	}
//	public void sort(){
// int[] arr = new int[]{3,4,5,2,5,63,2,5};
// //...
//	}
	
	public void info(a){
		/ / error
// public void swim(){
//			
/ /}}}Copy the code

1

Create a Person class with the following definition:

public class Person {
	String name;
	int age;
	/* * sex:1 indicates male * sex:0 indicates female */
	int sex;
	
	public void study(a){
		System.out.println("studying");
	}
	
	public void showAge(a){
		System.out.println("age:" + age);
	}
	
	public int addAge(int i){
		age += i;
		returnage; }}Copy the code

The test class

/* * Request: * (1) create an object of the Person class, set the name, age, and sex properties of the object, * call the study method, and the string string "studying", * call the showAge() method to show the age value, * Call the addAge() method to increase the age value of the object by 2 years. * (2) Create a second object, perform the above operation, experience the relationship between different objects of the same class. * * /
public class PersonTest {
	public static void main(String[] args) {
		Person p1 = new Person();
		
		p1.name = "Tom";
		p1.age = 18;
		p1.sex = 1;
		
		p1.study();
		
		p1.showAge();
		
		int newAge = p1.addAge(2);
		System.out.println(p1.name + "The age is" + newAge);
		
		System.out.println(p1.age);	/ / 20
		
		/ / * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
		Person p2 = new Person();
		p2.showAge();	/ / 0
		p2.addAge(10);
		p2.showAge();	/ / 10
		
		p1.showAge();	/ / 20}}Copy the code

2

/* * 2. Using object-oriented programming method, design class Circle to calculate the area of the Circle. * /
/ / test class
public class CircleTest {
	public static void main(String[] args) {
		Circle c1 = new Circle();
		
		c1.radius = 2.1;
		
		// Corresponding mode 1:
// double area = c1.findArea();
// System.out.println(area);
		
		// Corresponding mode 2:
		c1.findArea();
		// Wrong call
		double area = c1.findArea(3.4); System.out.println(area); }}/ / round: 3.14 * r * r
class Circle{
	/ / property
	double radius;
	
	// Circle area method
	// Method 1:
//	public double findArea(){
// double area = 3.14 * radius * radius;
// return area;
//	}	
	// Method 2:
	public void findArea(a){
		double area = Math.PI * radius * radius;
		System.out.println("The area is :" + area);
	}
	// Error:
	public double findArea(Double r){
		double area = 3.14 * r * r;
		returnarea; }}Copy the code

3, Practice 3

/* * 3.1 Declare a method, print a 10*8 * rectangle in the method, and call the method in the main method. * 3.2 Modify the previous program, in the method method, in addition to printing a 10*8 * rectangle, then calculate the area of the rectangle, * and take it as the method return value. This method is called in the main method, receives the returned area value and prints it. * * 3.3 Modify the previous program, provide two parameters m and n in the method method, print an m*n * rectangle, * and calculate the area of the rectangle, as the method return value. This method is called in the main method, receives the returned area value and prints it. * * /
public class ExerTest {
	
	public static void main(String[] args) {
		
		ExerTest esr = new ExerTest();
		/ / 3.1 test
// esr.method();
		
		/ / 3.2 test
		// Method 1:
// int area = esr.method();
// system.out. println(" area = "+ area); // system.out. println(" area =" + area);
		
		// Method 2:
// system.out.println (" area :" + esr.method());
		
		/ / 3.3 test
		System.out.println("The area is :" + esr.method(6.5));
	}
	/ / 3.1
//	public void method(){
// for(int i = 0; i < 10; i++){
//			for(int j = 0;j < 8;j++){
// System.out.print("* ");
/ /}
// System.out.println();
/ /}
//	}
	
	/ / 3.2
//	public int method(){
// for(int i = 0; i < 10; i++){
//			for(int j = 0;j < 8;j++){
// System.out.print("* ");
/ /}
// System.out.println();
/ /}
// return 10 * 8;
//	}
	
	/ / 3.3
	public int method(int m,int n){
		for(int i = 0; i < m; i++){for(int j = 0; j < n; j++){ System.out.print("*");
			}
			System.out.println();
		}
		returnm * n; }}Copy the code

4, Exercise 4

/* * state(int); score(int); /* * state(int); * Create 20 student objects, student numbers 1 to 20, grade and grade are determined by random numbers. * Problem 1: Print out information for grade 3 students (state value is 3). 1) Generate a random number: math.random (), return type double; * 2) Round: math.round (double d), return type long. * * /
public class StudentTest {
	public static void main(String[] args) {
		// Declare an array of type Student
		Student[] stu = new Student[20];
		
		for(int i = 0; i <stu.length; i++){// Assign values to array elements
			stu[i] = new Student();
			// Assign a value to the property of the Student object
			stu[i].number = i + 1;
			/ / grade: [1, 6]
			stu[i].state = (int)(Math.random() * (6 - 1 + 1) + 1);
			/ / grade: [0100]
			stu[i].score = (int)(Math.random() * (100 - 0 + 1));
		}
		
		// Iterate over the student array
		for(int i = 0; i < stu.length; i++){// System.out.println(stu[i].number + "," + stu[i].state
// + "," + stu[i].score);
			
			System.out.println(stu[i].info());
		}
		System.out.println("********* The following is question 1*********");
		
		// Print out the information for grade 3 (state = 3).
		for(int i = 0; i < stu.length; i++){if(stu[i].state == 3){
				System.out.println(stu[i].info());
			}
		}
		System.out.println("******** The following is question 2**********");
		
		// Query 2: Use bubble sort to sort by student score and iterate over all student information.
		for(int i = 0; i < stu.length -1; i++){for(int j = 0; j <stu.length -1- i; j++){if(stu[j].score >stu[j+1].score){
					// If the order needs to be reversed, it is the element of the array, the Student object!!
					Student temp = stu[j];
					stu[j] = stu[j+1];
					stu[j+1] = temp; }}}// Iterate over the student array
		for(int i = 0;i < stu.length;i++){
			System.out.println(stu[i].info());
		}
		
	}
}
class Student{
	int number;	/ / student id
	int state;	/ / grade
	int score;	/ / result
	
	// How to display student information
	public String info(a){
		return "Student number." + number + Grade ",," + state + ", result:"+ score; }}Copy the code

4-1. Exercise 4 optimization

/* * state(int); score(int); /* * state(int); * Create 20 student objects, student numbers 1 to 20, grade and grade are determined by random numbers. * Problem 1: Print out information for grade 3 students (state value is 3). 1) Generate a random number: math.random (), return type double; * 2) Round: math.round (double d), return type long. * * This code is an improvement on studenttest. Java that encapsulates the ability to manipulate arrays in methods. * /
public class StudentTest2 {
	public static void main(String[] args) {
		// Declare an array of type Student
		Student2[] stu = new Student2[20];
		
		for(int i = 0; i <stu.length; i++){// Assign values to array elements
			stu[i] = new Student2();
			// Assign a value to the property of the Student object
			stu[i].number = i + 1;
			/ / grade: [1, 6]
			stu[i].state = (int)(Math.random() * (6 - 1 + 1) + 1);
			/ / grade: [0100]
			stu[i].score = (int)(Math.random() * (100 - 0 + 1));
		}
		
		StudentTest2 test = new StudentTest2();
		
		// Iterate over the student array
		test.print(stu);
		
		System.out.println("********* The following is question 1*********");
		
		// Print out the information for grade 3 (state = 3).
		test.searchState(stu, 3);
		System.out.println("******** The following is question 2**********");
		
		// Query 2: Use bubble sort to sort by student score and iterate over all student information.
		test.sort(stu);
		
		// Iterate over the student array
		for(int i = 0; i < stu.length; i++){ System.out.println(stu[i].info()); }}/ * * * *@DescriptionIterates the Student[] array */
	public void print(Student2[] stu){
		for(int i = 0; i < stu.length; i++){ System.out.println(stu[i].info()); }}/ * * * *@DescriptionFind learning information */ for the specified grade in the Student array
	public void searchState(Student2[] stu,int state){
		for(int i = 0; i < stu.length; i++){if(stu[i].state == state){ System.out.println(stu[i].info()); }}}/ * * * *@DescriptionSort the Student array */
	public void sort(Student2[] stu){
		for(int i = 0; i < stu.length -1; i++){for(int j = 0; j <stu.length -1- i; j++){if(stu[j].score >stu[j+1].score){
					// If the order needs to be reversed, it is the element of the array, the Student object!!
					Student2 temp = stu[j];
					stu[j] = stu[j+1];
					stu[j+1] = temp;
				}
			}
		}
	}
}
class Student2{
	int number;	/ / student id
	int state;	/ / grade
	int score;	/ / result
	
	// How to display student information
	public String info(a){
		return "Student number." + number + Grade ",," + state + ", result:"+ score; }}Copy the code

4.2. Understand that “Everything is an Object”

/* 1. In the Java language category, we all encapsulate functions and structures into classes, and invoke specific functional structures through class instantiation. * "Scanner,String, etc. *" File: File * "Network resource: URL * 2 When it comes to the interaction between the Java language and the front-end HTML and the back-end database, the structure of the front and back end is reflected as classes and objects when interacting at the Java level. * /
Copy the code

4.3 Object array memory parsing

/* A reference type variable can store only two types of values: null or address values (including variable types) */
Student[] stus= newStudent[5];
stus[0] = new Student();
sysout(stus[0].state);/ / 1
sysout(stus[1]);//null
sysout(stus[1].number);/ / exception
stus[1] = new Student();
sysout(stus[1].number);/ / 0

class Student{
  int number;/ / student id
  int state = 1;/ / grade
  int score;/ / result
}
Copy the code

4.4. Use of anonymous objects

1. Understanding: We create an object that does not display the value assigned to a variable name. That is, anonymous objects. * 2. Characteristics: Anonymous objects can only be called once. * 3. Use: as follows */
public class InstanceTest {
	public static void main(String[] args) {
		Phone p = new Phone();
// p = null;
		System.out.println(p);
		
		p.sendEmail();
		p.playGame();
		
		// Anonymous objects
// new Phone().sendEmail();
// new Phone().playGame();
		
		new Phone().price = 1999;
		new Phone().showPrice();	/ / 0.0
		
		/ / * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
		PhoneMall mall = new PhoneMall();
// mall.show(p);
		// Use of anonymous objects
		mall.show(newPhone()); }}class PhoneMall{
	
	public void show(Phone phone){ phone.sendEmail(); phone.playGame(); }}class Phone{
	double price;	/ / price
	
	public void sendEmail(a){
		System.out.println("Send an email");
	}
	public void playGame(a){
		System.out.println("Play video games");
	}
	public void showPrice(a){
		System.out.println("The price of mobile phone is :"+ price); }}Copy the code

4.5. Utility classes for customizing arrays

1. Tool classes

/* * Custom array utility class */
public class ArrayUtil {

	// Find the maximum value of the array
	public int getMax(int[] arr) {
		int maxValue = arr[0];
		for (int i = 1; i < arr.length; i++) {
			if(maxValue < arr[i]) { maxValue = arr[i]; }}return maxValue;
	}

	// Find the minimum value of the array
	public int getMin(int[] arr) {
		int minValue = arr[0];
		for (int i = 1; i < arr.length; i++) {
			if(minValue > arr[i]) { minValue = arr[i]; }}return minValue;
	}

	// find the sum of the array
	public int getSum(int[] arr) {
		int sum = 0;
		for (int i = 0; i < arr.length; i++) {
			sum += arr[i];
		}
		return sum;
	}

	// Average the array
	public int getAvg(int[] arr) {
		int avgValue = getSum(arr) / arr.length;
		return avgValue;
	}

	// Invert the array
	public void reverse(int[] arr) {
		for (int i = 0; i < arr.length / 2; i++) {
			int temp = arr[i];
			arr[i] = arr[arr.length - i - 1];
			arr[arr.length - i - 1] = temp; }}// Copy the array
	public int[] copy(int[] arr) {
		int[] arr1 = new int[arr.length];
		for (int i = 0; i < arr1.length; i++) {
			arr1[i] = arr[i];
		}
		return null;
	}

	// Array sort
	public void sort(int[] arr) {
		for (int i = 0; i < arr.length - 1; i++) {
			for (int j = 0; j < arr.length - 1 - i; j++) {
				if (arr[j] > arr[j + 1]) {
					int temp = arr[j];
					arr[j] = arr[j + 1];
					arr[j + 1] = temp; }}}}// go through the number group
	public void print(int[] arr) {
		System.out.print("[");
		for (int i = 0; i < arr.length; i++) {
			System.out.print(arr[i] + ",");
		}
		System.out.println("]");
	}

	// Find the specified element
	public int getIndex(int[] arr, int dest) {
		// Linear search
		for (int i = 0; i < arr.length; i++) {
			if (dest==arr[i]) {
				returni; }}return -1; }}Copy the code

2. Test classes

/ * * *@DescriptionTest class * */
public class ArrayUtilTest {


	public static void main(String[] args) {
		ArrayUtil util = new ArrayUtil();
		int[] arr = new int[] {32.5.26.74.0.96.14, -98.25};
		int max = util.getMax(arr);
		System.out.println("Maximum value is :" + max);
		
// system.out. print(" before sorting :");
// util.print(arr);
//		
// util.sort(arr);
// system.out. print(" sort :");
// util.print(arr);
		
		System.out.println("Search.");
		int index = util.getIndex(arr, 5);
		if(index > 0){
			System.out.println("Found, index address :" + index);
		}else{
			System.out.println("Not found."); }}}Copy the code

4.6 method Overload

/* overload loading... * * 1. Definition: More than one method with the same name is allowed in the same class, as long as they have different parameters or parameter types. * * "Two same different" : same class, same method name * Different parameter lists: Different number of parameters, different parameter types * * 2. Example: * Overloaded sort()/binarySearch() * * 3 from the Arrays class. Overloaded * is determined regardless of the method's return value type, permission modifier, parameter name, or method body. * * 4. How to determine a specified method when calling a method from an object: * method name -- parameter list */
public class OverLoadTest {
	
	public static void main(String[] args) {
		OverLoadTest test = new OverLoadTest();
		test.getSum(1.2);	// The first call, prints 1
	}

	// The following four methods constitute overloading
	public void getSum(int i,int j){
		System.out.println("1");
	}
	public void getSum(double d1,double d2){
		System.out.println("2");
	}
	public void getSum(String s,int i){
		System.out.println("3");
	}
	
	public void getSum(int i,String s){}// The following three are incorrect overloads
//	public int getSum(int i,int j){
// return 0;
//	}
	
//	public void getSum(int m,int n){
//		
//	}
	
//	private void getSum(int i,int j){
//		
//	}
}
Copy the code

1, for example,

1.Judge: andvoid show(int a,char b,double c){} Constitute the overload: a)void show(int x,char y,double z){} // no
b)int show(int a,double c,char b){} // yes
c) void show(int a,double c,char b){} // yes
d) boolean show(int c,char b){} // yes
e) void show(double c){} // yes 
f) double show(int x,char y,double z){} // no
g) void shows(a){double c} // no
Copy the code

2, programming,

/* * 1. Write a program to define three overloaded methods and call them. The method is called mOL. * Three methods take one int argument, two int arguments, and one string argument, respectively. * Square and print the result, multiply and print the result, print the string information. * Three methods are called separately with arguments in the main () method of the main class. * 2. Define three overloaded methods Max (), * the first one maximizes two int values, * the second one maximizes two double values, and * the third one maximizes three double values and calls each of the three methods. * * /
public class OverLoadever {
	
	public static void main(String[] args) {
		OverLoadever test = new OverLoadever();
		//1. Call three methods
		test.mOL(5);
		test.mOL(6.4);
		test.mOL("fg");
		
		//2. Call three methods
		int num1 = test.max(18.452);
		System.out.println(num1);
		double num2 = test.max(5.6, -78.6);
		System.out.println(num2);
		double num3 = test.max(15.52.42);
		System.out.println(num3);
	}

	The following three methods constitute an overload
	public void mOL(int i){
		System.out.println(i*i);
	}
	public void mOL(int i,int j){
		System.out.println(i*j);
	}
	public void mOL(String s){
		System.out.println(s);
	}
	
	//2. The following three methods constitute an overload
	public int max(int i,int j){
		return (i > j) ? i : j;
	}
	public double max(double i,double j){
		return (i > j) ? i : j;
	}
	public double max(double d1,double d2,double d3){
		double max = (d1 > d2) ? d1 : d2;
		return(max > d3) ? max : d3; }}Copy the code

4.7. Variable number of parameters

JavaSE 5.0 provides a mechanism called Varargs(Variable Number of arguments) that allows you to directly define parameters that can match multiple arguments. Thus, we can pass arguments with a variable number in a simpler way.

/* * Method of variable number parameter * 1. JDK 5.0 new content * 2. * 2.1 Format of the variable number parameter: Data type... Variable name * 2.2 When calling a method with variable number parameters, the number of arguments passed can be: 0, 1, 2... * 2.3 The methods of variable parameter have the same name as the Chinese method of this class, and the methods of different parameters constitute overloads. * 2.4 There is no overloading between arrays whose methods have the same names and whose parameters have the same types. The two cannot coexist. * 2.5 Variable parameters In a method parameter, must be declared at the end. * 2.6 Variable Number parameters In a method, you can declare at most one variable parameter. * /
public class MethodArgs {

	public static void main(String[] args) {
		MethodArgs test = new MethodArgs();
		test.show(12);
		// test.show("hell0");
		// test.show("hello","world");
		// test.show();

		test.show(new String[] { "AA"."BB"."CC" });
	}

	public void show(int i) {}// public void show(String s){
	// System.out.println("show(String)");
	// }
	public void show(String... strs) {
		System.out.println("show(String ... strs)");


		for (int i = 0; i < strs.length; i++) { System.out.println(strs[i]); }}// This method cannot coexist with the previous method
	// public void show(String[] strs){
	//
	// }

	public void show(int i, String... strs) {}//The variable argument type String of the method show must be the last parameter
//	public void show(String... strs,int i,) {
//
//	}
}
Copy the code

4.8. Value transfer mechanism of method parameters (key!!)

/* * Assignment to a variable * * If the variable is a primitive data type, then the assignment is to the value of the data that the variable holds. * If the variable is a reference data type, the value assigned is the address value of the data the variable holds. * * /
public class ValueTransferTest {

	public static void main(String[] args) {
		
		System.out.println("********** Basic data type: ***********");
		int m = 10;
		int n = m;
		
		System.out.println("m = " + m + ", n = " + n);
		
		n = 20;
		
		System.out.println("m = " + m + ", n = " + n);

		System.out.println("*********** Quoted data type :********");
		
		Order o1 = new Order();
		o1.orderId = 1001;
		
		Order o2 = o1;	// Assign o1 and o2 to the same object entity in the heap space
		System.out.println("o1.orderId = " + o1.orderId + ",o2.orderId = " + o2.orderId);
		
		o2.orderId = 1002;
		System.out.println("o1.orderId = " + o1.orderId + ",o2.orderId = "+ o2.orderId); }}class Order{
	int orderId;
}
Copy the code

4.8.1,For basic data types

Parameter: the argument declared in parentheses when the method is defined. Parameter: the data actually passed to the parameter when the method is called * * 2. Value passing mechanism: * If the argument is a primitive data type, then the argument is assigned the value of the data stored by the argument. * /
public class ValueTransferTest1 {

	public static void main(String[] args) {
		
		int m = 10;
		int n = 20;
		
		System.out.println("m = " + m + ", n = " + n);
		// The operation that swaps the values of two variables
// int temp = m;
// m = n;
// n = temp;
		
		ValueTransferTest1 test = new ValueTransferTest1();
		test.swap(m, n);
		
		System.out.println("m = " + m + ", n = " + n);
		
	}
	
	public void swap(int m,int n){
		inttemp = m; m = n; n = temp; }}Copy the code

4.8.2,For reference data types

/* * If the argument is a reference data type, the argument is assigned to the address of the data stored in the argument. * /
public class ValueTransferTest2 {

	public static void main(String[] args) {
		Data data = new Data();
		
		data.m = 10;
		data.n = 20;
		
		System.out.println("m = " + data.m + ", n = " + data.n);

		// Swap m and n
// int temp = data.m;
// data.m = data.n;
// data.n = temp;

		ValueTransferTest2 test = new ValueTransferTest2();
		test.swap(data);
		
		System.out.println("m = " + data.m + ", n = " + data.n);

	}
	
	public void swap(Data data){
		inttemp = data.m; data.m = data.n; data.n = temp; }}class Data{
	
	int m;
	int n;
}
Copy the code

4.8.3,Exercise 1

public class TransferTest3{
	public static void main(String args[]){
		TransferTest3 test=new TransferTest3();
		test.first();
	}
	
	public void first(a){
		int i=5;
		Value v=new Value();
		v.i=25;
		second(v,i);
		System.out.println(v.i);
	}
	
	public void second(Value v,int i){
		i=0;
		v.i=20;
		Value val=new Value();
		v=val;
		System.out.println(v.i+""+i); }}class Value {
	int i= 15;
} 
Copy the code

4.8.4,Ex 2

public static void method(int a,int b){
	a = a * 10;
	b = b * 20;
	System.out.println(a);
	System.out.println(b);
	System.exit(0);
}
Copy the code

4.8.5,Practice 3

Int [] arr = new int[]{12,3,3,34,56,77,432}; * Remove the first element from the value at each position in the array, resulting in the new value at that position. Iterate over the new array. * /
 
// Error
for(int i= 0; i < arr.length; i++){ arr[i] = arr[i] / arr[0];
}

// Use the following method
for(intI = arr. Length -1; i >=0; i--){ arr[i] = arr[i] / arr[0];
}

// Use the following method
int temp = arr[0];
for(int i= 0; i < arr.length; i++){ arr[i] = arr[i] / temp; }Copy the code

4.8.6,Exercise 4

/* * int[] arr = new int[10]; * System.out.println(arr); // Address value? * * char[] arr1 = new char[10]; * System.out.println(arr1); // Address value? * /
public class ArrayPrint {

	public static void main(String[] args) {
		int[] arr = new int[] {1.2.3};
        // Pass in an Object Object
		System.out.println(arr);/ / address values
		
		char[] arr1 = new char[] {'a'.'b'.'c'};
        // Pass in an array that iterates through the data
		System.out.println(arr1);//abc}}12345678910111213141516171819
Copy the code

4.8.7,Exercise 5: Passing objects as arguments to methods

(1) Define a Circle class with a radius attribute of type double representing the radius of the Circle and a findArea() method that returns the area of the Circle. * * (2) Define a class PassObject and define a method printAreas() as follows: Public void printAreas(Circle c,int time) public void printAreas(Circle c,int time) * for example, if times is 5, output the radius 1,2,3,4,5, and the corresponding circle area. * * (3) Call printAreas() in main and output the current radius value. * * /
public class Circle {

	double radius;	/ / radius
	
	// Return the circle's area
	public double findArea(a){
		returnradius * radius * Math.PI; }}Copy the code

PassObject class

public class PassObject {
	
	public static void main(String[] args) {
		PassObject test = new PassObject();
		
		Circle c = new Circle();
		
		test.printAreas(c, 5);
		
		System.out.println("no radius is:" + c.radius);
	}
	
	public void printAreas(Circle c,int time){
		
		System.out.println("Radius\t\tAreas");
		
		// Set the radius of the circle
		for(int i = 1; i <= time ; i++){ c.radius = i; System.out.println(c.radius +"\t\t" + c.findArea());
		}
		
		// reassign
		c.radius = time + 1; }}Copy the code

4.9 recursion method

/* * Use of recursive methods (understand) * 1. Recursive methods: a method body calls itself. * 2. Method recursion consists of an implicit loop that executes a piece of code repeatedly, but this repetition does not require loop control. * * 3. Recursion must recurse in a known direction, otherwise the recursion becomes infinite recursion, similar to an infinite loop. * * /
public class RecursionTest {

	public static void main(String[] args) {

		Example 1: Calculate the sum of all natural numbers between 1 and 100
		/ / method 1:
		int sum = 0;
		for (int i = 1; i <= 100; i++) {
			sum += i;
		}
		System.out.println("sum = " + sum);

		/ / method 2:
		RecursionTest test = new RecursionTest();
		int sum1 = test.getSum(100);
		System.out.println("sum1 = " + sum1);
	}

	// Example 1: Calculate the sum of all natural numbers between 1 and n
	public int getSum(int n) {

		if (n == 1) {
			return 1;
		} else {
			return n + getSum(n - 1); }}// Example 2: Compute the product of all natural numbers between 1 and n
	// Return (n!) The algorithm of
	public int getSum1(int n) {


		if (n == 1) {
			return 1;
		} else {
			return n * getSum1(n - 1); }}}Copy the code

1

public class RecursionTest {

	public static void main(String[] args) {

		int value = test.f(10);
		System.out.println(value);
	}

	/ / example 3: there is a known sequence: f (0) = 1, f (1) = 4, f (n + 2) = 2 * f (n + 1) + f (n),
	// where n is an integer greater than 0, find f(10).
	public int f(int n){
		if(n == 0) {return 1;
		}else if(n == 1) {return 4;
		}else{
			return 2*f(n-1) + f(n-2); }}/ / case 4: a known sequence: f (20) = 1, f = 4 (21), f (n + 2) = 2 * f (n + 1) + f (n),
	// where n is an integer greater than 0, find f(10).
	public int f1(int n){
		if(n == 20) {return 1;
		}else if(n == 21) {return 4;
		}else{
			return 2*f1(n-1) + f1(n-2); }}}Copy the code

2

/* * Enter a number n to calculate the NTH Fibonacci number * 1 1 2 3 5 8 13 21 34 55 Calculate the NTH value of the Fibonacci sequence and print out the entire sequence * */
public class Recursion2 {

	public static void main(String[] args) {
		
		Recursion2 test = new Recursion2();
		int value = test.f(10);
		System.out.println(value);
	}
	
	public int f(int n) {

		if (n == 1 || n == 2) {
			return 1;
		} else {
			return f(n - 1) + f(n - 2); }}}Copy the code

5. One of the object-oriented features: encapsulation and hiding

1. Introduction and embodiment of encapsulation

Why encapsulation? What does encapsulation do and what does it mean? I need to use the washing machine, just press the switch and wash mode. Is it necessary to know the inside of the washing machine? Is it necessary to touch the motor? I’m going to drive…

2. Our program design pursues “high cohesion, low coupling”.

High cohesion: The internal data manipulation details of the class are done by itself, without external interference; Low coupling: Only a few methods are exposed for use.

3. Hide the internal complexity of objects and expose only simple interfaces.

Easy to call outside, so as to improve the system scalability, maintainability. In layman’s terms, hide what needs to be hidden and expose what needs to be exposed. That’s the idea of encapsulation.

* When we create a class of objects, we can pass "object". Property "to assign a value to an object's property. Here, assignment is constrained by the data type and storage scope of the * attribute. But beyond that, there are no other constraints. In practice, however, we often need to place additional constraints on assigning * to attributes. This condition is not reflected in the property declaration, we can only add the condition through the method. For example, setLegs * in the meantime, we need to prevent the user from using the "object" again. Property "to assign a value to a property. Declare the property as private * --. In this case, encapsulation is applied to the property. * * We privatized the class attributes and provided public methods to get (getXxx) and set (setXxx) * * Extension: Encapsulation: ① above, ② singleton pattern ③ private method * */
public class AnimalTest {

	public static void main(String[] args) {
		Animal a = new Animal();
		a.name = "Rhubarb";
// a.age = 1;
//		a.legs = 4;//The field Animal.legs is not visible
		
		a.show();
		
// a.legs = -4;
// a.setLegs(6);
		a.setLegs(-6);
		
//		a.legs = -4;//The field Animal.legs is not visiblea.show(); System.out.println(a.name); System.out.println(a.getLegs()); }}class Animal{
	
	String name;
	private int age;
	private int legs; // Number of legs
	
	// Set the attributes
	public void setLegs(int l){
		if(l >= 0 && l % 2= =0){
			legs = l;
		}else{
			legs = 0; }}// Get attributes
	public int getLegs(a){
		return legs;
	}
	
	public void eat(a){
		System.out.println("Animal feeding.");
	}
	
	public void show(a){
		System.out.println("name = " + name + ",age = " + age + ",legs = " + legs);
	}
	
	// Provide get and set methods on the attribute age
	public int getAge(a){
		return age;
	}
	
	public void setAge(int a){ age = a; }}Copy the code

5.1 Understanding and testing of the four permission modifiers

The Java permission modifiers public, protected, default, and private precede a class’s member definition to restrict access to members of that class.

Only public and default(the default) can be used for class permission modifications.

  • The public class can be accessed anywhere.
  • The default class can only be accessed by classes inside the same package.

1, the Order class

/* * 3, the encapsulation of the need for permission modifier. There are four types of permissions: (in descending order)private, default, protected, public * 2.4 Types of permissions that modify classes and their internal structures: properties, methods, constructors, inner classes * 3. In particular, four permissions can be used to modify the inner structure of a class: attribute, method, constructor, inner class * To modify a class, you can only use: default, public * summary encapsulation: Java provides four permission modifiers to modify the inner structure of a class, the method to reflect the visibility of the class and the inner structure of the class. * * /
public class Order {

	private int orderPrivate;
	int orderDefault;
	public int orderPublic;
	
	private void methodPrivate(a){
		orderPrivate = 1;
		orderDefault = 2;
		orderPublic = 3;
	}
	
	void methodDefault(a){
		orderPrivate = 1;
		orderDefault = 2;
		orderPublic = 3;
	}
	
	public void methodPublic(a){
		orderPrivate = 1;
		orderDefault = 2;
		orderPublic = 3; }}Copy the code

2, OrderTest class

public class OrderTest {

	public static void main(String[] args) {
		
		Order order = new Order();
		
		order.orderDefault = 1;
		order.orderPublic = 2;
		// Outside the Order class, private structures are not callable
//		order.orderPrivate = 3;//The field Order.orderPrivate is not visible
		
		order.methodDefault();
		order.methodPublic();
		// Outside the Order class, private structures are not callable
//		order.methodPrivate();//The method methodPrivate() from the type Order is not visible}}Copy the code

OrderTest class for different packages of the same project

import github.Order;

public class OrderTest {

	public static void main(String[] args) {
		Order order = new Order();
		
		order.orderPublic = 2;
		After leaving the Order class, the private structure, the default declaration structure, is not callable
// order.orderDefault = 1;
//		order.orderPrivate = 3;//The field Order.orderPrivate is not visible
		
		order.methodPublic();
		After leaving the Order class, the private structure, the default declaration structure, is not callable
// order.methodDefault();
//		order.methodPrivate();//The method methodPrivate() from the type Order is not visible}}Copy the code

5.2 encapsulation exercises

/* * 1. Create a program that defines two classes: the Person and PersonTest classes. * The definition is as follows: setAge() is used to set a person's legal age (0-130), and getAge() is used to return the person's age. * * /
public class Person {

	private int age;
	
	public void setAge(int a){
		if(a < 0 || a > 130) {// throw new RuntimeException(" Incoming data is invalid ");
			System.out.println("Incoming data is illegal");
			return;
		}
		
		age = a;
		
	}
	
	public int getAge(a){
		return age;
	}
	
	// Never write like this!!
	public int doAge(int a){
		age = a;
		returnage; }}Copy the code

3. Test classes

/* * Instantiate the Person object B in the PersonTest class. * Call the setAge() and getAge() methods to experience Java encapsulation. * /
public class PersonTest {

	public static void main(String[] args) {
		Person p1 = new Person();
// p1.age = 1; // Failed to compile
		
		p1.setAge(12);
		
		System.out.println("Age :"+ p1.getAge()); }}Copy the code

6. Constructors (constructors)

6.1 understanding of constructors

Constructor (); constructor (); constructor (); Create object * * 2. Initialize object properties * * 2. If no constructor for the class is displayed, the system provides a constructor for empty parameters by default. * 2. Define the constructor's format: * Permission modifier class name (parameter list) {} * 3. Multiple constructors defined in a class constitute overloads on each other. * 4. Once the constructor for the class is defined, the system no longer provides the default null parameter constructor. * 5. A class must have at least one constructor */
public class PersonTest {

	public static void main(String[] args) {
		// Create an object for the class :new + constructor
		Person p = new Person();	//Person() that's the constructor
		
		p.eat();
		
		Person p1 = new Person("Tom"); System.out.println(p1.name); }}class Person{
	/ / property
	String name;
	int age;
	
	/ / the constructor
	public Person(a){
		System.out.println("Person()......");
	}
	
	public Person(String n){
		name = n;
	}
	
	public Person(String n,int a){
		name = n;
		age = a;
	}
	
	/ / method
	public void eat(a){
		System.out.println("People eat.");
	}
	
	public void study(a){
		System.out.println("People learn"); }}Copy the code

1

/* 2. Add a constructor to the Person class as defined above, and use the constructor to set everyone's age property to 18. * * /
public class Person {

	private int age;
	
	public Person(a){
		age = 18; }}public class PersonTest {

	public static void main(String[] args) {
		Person p1 = new Person();

		System.out.println("Age :"+ p1.getAge()); }}Copy the code

2

/* create a Person object and initialize the age and name attributes of the object. * /
public class Person {

	private int age;
	private String name;
	
	public Person(a){
		age = 18;
	}
	
	public Person(String n,int a){
		name = n;
		age = a;
	}
	
	public void setName(String n){
		name = n;
	}
	
	public String getName(a){
		return name;
	}
	
	public void setAge(int a){
		if(a < 0 || a > 130) {// throw new RuntimeException(" Incoming data is invalid ");
			System.out.println("Incoming data is illegal");
			return;
		}
		
		age = a;
		
	}
	
	public int getAge(a){
		returnage; }}public class PersonTest {

	public static void main(String[] args) {
		
		Person p2 = new Person("Tom".21);
		
		System.out.println("name = " + p2.getName() + ",age = "+ p2.getAge()); }}Copy the code

3, Practice 3

/* * Write two classes, TriAngle and TriAngleTest, where TriAngle declares private base and height, and public methods access private variables. In addition, provide the necessary constructors for the class. Another class uses these common methods to calculate the area of a triangle. * * /
public class TriAngle {

	private double base;/ / bottom side
	private double height;/ / high
	
	public TriAngle(a){}public TriAngle(double b,double h){
		base = b;
		height = h;
	}
	
	public void setBase(double b){
		base = b;
	}
	
	public double getBase(a){
		return base;
	}
	
	public void setHeight(double h){
		height = h;
	}
	
	public double getHeight(a){
		returnheight; }}public class TriAngleTest {

	public static void main(String[] args) {
		
		TriAngle t1 = new TriAngle();
		t1.setBase(2.0);
		t1.setHeight(2.5);
/ / t1. Base = 2.5; //The field TriAngle.base is not visible
/ / t1. Height = 4.3;
		System.out.println("base : " + t1.getBase() + ",height : " + t1.getHeight());
		
		TriAngle t2 = new TriAngle(5.1.5.6);
		System.out.println("面积 : " + t2.getBase() * t2.getHeight() / 2); }}Copy the code

6.2 Summarize the process of attribute assignment

/* * Summary: the order in which attributes are assigned * * ① default initialization * ② explicit initialization * ③ constructor assignment * ④ through "object. Method "or" object. Attribute, assign * * the order of the above operations :① - ② - ③ - ④ * */
public class UserTest {

	public static void main(String[] args) {
		User u = new User();
		
		System.out.println(u.age);
		
		User u1 = new User(2);
		
		u1.setAge(3); System.out.println(u1.age); }}class User{
	String name;
	int age = 1;
	
	public User(a){}public User(int a){
		age = a;
	}
	
	public void setAge(int a){ age = a; }}Copy the code

6.3. Use of JavaBean

/* * Javabeans are reusable components written in the Java language. * Javabeans are Java classes that meet the following criteria: * > Class is public * > has a public constructor with no arguments * > has attributes, and has corresponding get and set methods * */
public class Customer {
	
	private int id;
	private String name;

	public Customer(a){}public void setId(int i){
		id = i;
	}
	
	public int getId(a){
		return id;
	}
	
	public void setName(String n){
		name = n;
	}
	
	public String getName(a){
		returnname; }}Copy the code

6.4. UML Class Diagrams

  • For public type, – for private type, and # for protected type
  • Method type (+, -) Method name (parameter name: parameter type) : return value type

7, the use of the keyword: this

7.1. This invokes properties, methods, and constructors

This modifies and calls properties, methods, and constructors * * 2. This modifies properties and methods: * this is the current object, or the object currently being created. * * 2.1 In class methods, we can use the "this. attribute "or "this". Method "to call the current object properties and methods. * Usually, we choose to omit "this." In particular, if the method parameter has the same name as the class attribute, we must explicitly use "this "*. ", indicating that the variable is an attribute, not a parameter. * * 2.2 In class constructors, we can use either the "this. attribute "or "this." Method "to call the properties and methods of the object being created. * But, more often than not, we choose to omit "this." In particular, if the constructor parameter has the same name as the class attribute, we must explicitly use "this "*. ", indicating that the variable is an attribute, not a parameter. * * this calls the constructor * ① We can explicitly call other overloaded constructors in the class using the "this "method. * ② The constructor cannot call itself with "this ". * ③ If n constructors are declared in a class, at most n-1 constructors use this(parameter list). * ④ "this(parameter list)" must be declared on the first line of the class's constructor! * ⑤ In a constructor of a class, you can only declare at most one "this ". * /
public class PersonTest {

	public static void main(String[] args) {
		Person p1 = new Person();
		
		p1.setAge(1);
		System.out.println(p1.getAge());
		
		p1.eat();
		System.out.println();
		
		Person p2 = new Person("jerry" ,20); System.out.println(p2.getAge()); }}class Person{
	
	private String name;
	private int age;
	
	public Person(a){
		this.eat();
		String info = "When initializing a Person, consider the following: 1,2,3,4... (40 lines of code)";
		System.out.println(info);
	}
	
	public Person(String name){
		this(a);this.name = name;
	}
	
	public Person(int age){
		this(a);this.age = age;
	}
	
	public Person(String name,int age){
		this(age);	// a way to call the constructor
		this.name = name;
// this.age = age;
	}
	
	public void setNmea(String name){
		this.name = name;
	}
	
	public String getName(a){
		return this.name;
	}
	
	public void setAge(int age){
		this.age = age;
	}
	
	public int getAge(a){
		return this.age;
	}
	
	public void eat(a){
		System.out.println("People eat.");
		this.study();
	}
	
	public void study(a){
		System.out.println("Learning"); }}Copy the code

7.2. Practice this

1, the Boy

public class Boy {

	private String name;
	private int age;
	
	public void setName(String name){
		this.name = name;
	}
	
	public String getName(a){
		return name;
	}
	
	public void setAge(int ahe){
		this.age = age;
	}
	
	public int getAge(a){
		return age;
	}
	
	public Boy(String name, int age) {
		this.name = name;
		this.age = age;
	}


	public void marry(Girl girl){
		System.out.println("I want to marry." + girl.getName());
	}
	
	public void shout(a){
		if(this.age >= 22){
			System.out.println("Consider marriage.");
		}else{
			System.out.println("Study hard."); }}}Copy the code

2, Girl

public class Girl {

	private String name;
	private int age;
	
	public String getName(a) {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	
	public Girl(a){}public Girl(String name, int age) {
		this.name = name;
		this.age = age;
	}
	
	public void marry(Boy boy){
		System.out.println("I want to marry." + boy.getName());
	}
	/ * * * *@DescriptionCompare the size of two objects *@author subei
	  * @date9:17:35 am, 21 April 2020 *@param girl
	  * @return* /
	public int compare(Girl girl){
// if(this.age >girl.age){
// return 1;
// }else if(this.age < girl.age){
// return -1;
// }else{
// return 0;
/ /}
		
		return this.age - girl.age; }}Copy the code

3. Test classes

public class BoyGirlTest {

	public static void main(String[] args) {
		
		Boy boy = new Boy(romeo.21);
		boy.shout();
		
		Girl girl = new Girl("Juliet".18);
		girl.marry(boy);
		
		Girl girl1 = new Girl("Zhu Yingtai".19);
		int compare = girl.compare(girl1);
		if(compare > 0){
			System.out.println(girl.getName() + "Big");
		}else if(compare < 0){
			System.out.println(girl1.getName() + "Big");
		}else{
			System.out.println("The same"); }}}Copy the code

2

The Account class

public class Account {

	private int id; / / account
	private double balance; / / the balance
	private double annualInterestRate; / / apr

	public void setId(int id) {}public double getBalance(a) {
		return balance;
	}

	public void setBalance(double balance) {
		this.balance = balance;
	}

	public double getAnnualInterestRate(a) {
		return annualInterestRate;
	}

	public void setAnnualInterestRate(double annualInterestRate) {
		this.annualInterestRate = annualInterestRate;
	}

	public int getId(a) {
		return id;
	}

	public void withdraw(double amount) { / / make a withdrawal
		if(balance < amount){
			System.out.println("Insufficient balance, withdrawal failed.");
			return;
		}
		balance -= amount;
		System.out.println("Successfully removed" + amount);
	}

	public void deposit(double amount) { / / save
		if(amount > 0){
			balance += amount;
			System.out.println("Successful deposit"+ amount); }}public Account(int id, double balance, double annualInterestRate) {
		this.id = id;
		this.balance = balance;
		this.annualInterestRate = annualInterestRate; }}Copy the code

The Customer class

public class Customer {

	private String firstName;
	private String lastName;
	private Account account;

	public Customer(String f, String l) {
		this.firstName = f;
		this.lastName = l;
	}

	public String getFirstName(a) {
		return firstName;
	}

	public String getLastName(a) {
		return lastName;
	}

	public Account getAccount(a) {
		return account;
	}

	public void setAccount(Account account) {
		this.account = account; }}Copy the code

, CustomerTest class

/* * Write a test program. * (1) Create a Customer named Jane Smith with account number 1000, * balance of $2000 and annual interest rate of 1.23%. * (2) Execute on Jane Smith. Deposit 100 yuan and withdraw 960 yuan. And withdraw another 2,000 yuan. Customer [Smith, Jane] has an account: Id is 1000, * annualInterestRate is 1.23%, balance is 1140.0 * */
public class CustomerTest {

	public static void main(String[] args) {
		Customer cust = new Customer("Jane" , "Smith");
		
		Account acct = new Account(1000.2000.0.0123);
		
		cust.setAccount(acct);
		
		cust.getAccount().deposit(100); / / in 100
		cust.getAccount().withdraw(960); / / draw money 960
		cust.getAccount().withdraw(2000); / / draw money 2000
		
		System.out.println("Customer[" + cust.getLastName() + cust.getFirstName() + "] has a account: id is "
				+ cust.getAccount().getId() + ",annualInterestRate is " + cust.getAccount().getAnnualInterestRate() * 100 + "%, balance is "+ cust.getAccount().getBalance()); }}Copy the code

3, Practice 3

The Account class

public class Account {

	private double balance;

	public double getBalance(a) {
		return balance;
	}

	public Account(double init_balance){
		this.balance = init_balance;
	}
	
	// Save money
	public void deposit(double amt){
		if(amt > 0){
			balance += amt;
			System.out.println("Save successfully"); }}// Withdraw money
	public void withdraw(double amt){
		if(balance >= amt){
			balance -= amt;
			System.out.println("Successful withdrawal.");
		}else{
			System.out.println("Insufficient balance"); }}}Copy the code

The Customer class

public class Customer {

	private String firstName;
	private String lastName;
	private Account account;
	
	public String getFirstName(a) {
		return firstName;
	}
	public String getLastName(a) {
		return lastName;
	}
	public Account getAccount(a) {
		return account;
	}
	public void setAccount(Account account) {
		this.account = account;
	}
	public Customer(String f, String l) {
		this.firstName = f;
		this.lastName = l; }}Copy the code

Bank class

public class Bank {

	private int numberOfCustomers;	// Count the number of customers
	private Customer[] customers;	// Store an array of customers
	
	public Bank(a){
		customers = new Customer[10];
	}
	
	// Add a client
	public void addCustomer(String f,String l){
		Customer cust = new Customer(f,l);
// customers[numberOfCustomers] = cust;
// numberOfCustomers++;
		customers[numberOfCustomers++] = cust;
	}

	// Get the number of customers
	public int getNumberOfCustomers(a) {
		return numberOfCustomers;
	}

	// Get the client at the specified location
	public Customer getCustomers(int index) {
// return customers; // An exception may be reported
		if(index >= 0 && index < numberOfCustomers){
			return customers[index];
		}
		
		return null; }}Copy the code

BankTest class

public class BankTest {

	public static void main(String[] args) {
		
		Bank bank = new Bank();
		
		bank.addCustomer("Jane"."Smith");	
		
		bank.getCustomers(0).setAccount(new Account(2000));
		
		bank.getCustomers(0).getAccount().withdraw(500);
		
		double balance = bank.getCustomers(0).getAccount().getBalance();
		
		System.out.println(Customer: + bank.getCustomers(0).getFirstName() + The account balance of "is:" + balance);
		
		System.out.println("* * * * * * * * * * * * * * * * * * * * * * * * * * *");
		bank.addCustomer("Thousands of miles"."Yang");
		
		System.out.println("Number of bank customers is:"+ bank.getNumberOfCustomers()); }}Copy the code

8. Use of keywords: package, import

8.1. Keyword — package

/* * 1. To better implement the management of classes in the project, provide the concept of package * 2. Use package to declare the package to which a class or interface belongs, in the first line of the source file * 3. Packages belong to identifiers and follow the naming rules of identifiers and the specification "by name" * 4. Each "." Once, it represents a layer of file directories. * * Add: You cannot name interfaces or classes with the same name in the same package. * You can name interfaces and classes with the same name in different packages. * * /
public class PackageImportTest {}Copy the code

Introduction to the main packages in the JDK

1.Java.lang ---- contains some of the core Java language classes, such as String, Math, Integer, System, and Thread, that provide common functionality2.Java.net ---- contains classes and interfaces for performing network-related operations.3.Java.io ---- contains classes that provide a variety of input/output functions.4.Java.util ---- contains utility classes such as a collection framework class that defines system features, interfaces, and functions related to using a date calendar.5.Java.text ---- contains classes related to Java formatting6.Java.sql ---- contains Java classes/interfaces for JDBC database programming7.Awt ---- contains classes that make up the abstractwindowtoolkits that are used to build and manage the graphical user interface (GUI) of an application. B/S C/SCopy the code

8.2. MVC design pattern

MVC is one of the commonly used design patterns, which divides the whole program into three layers: view model layer, controller layer and data model layer. This design mode of separating program input and output, data processing, and data display makes the program structure flexible and clear, and also describes the communication mode between each object of the program, reducing the coupling of the program.

8.3. Keyword – import

import java.util.*;

import account2.Bank;

* * import: import * 1. Explicitly import classes and interfaces from the specified package * 2 using the import structure in the source file. The declaration is between the package declaration and the class declaration * 3. If you need to import multiple structures, write them side by side * 4. You can use "XXX.*" to import all structures in the XXX package. * 5. Omit this import statement if the class or interface is imported from the java.lang package or from the current package. * 6. If you use a class with the same name under a different package in your code. You need to specify which class is being called using the full class name of the class. * 7. If classes from the java.a package have been imported. So if you want to use classes in subpackages of package A, you still need to import. * 8. Import static: call a static attribute or method from a specified class or interface
public class PackageImportTest {

	public static void main(String[] args) {
		String info = Arrays.toString(new int[] {1.2.3});
		
		Bank bank = new Bank();
		
		ArrayList list = new ArrayList();
		HashMap map = new HashMap();
		
		Scanner s = null;	
		
		System.out.println("hello");
		
		UserTest us = newUserTest(); }}Copy the code