java 4 (object-oriented)

java - object-oriented (on)

Table of contents

java is an object oriented language

1. Java classes and their members: attributes, methods, constructors; code blocks, inner classes

2. The three major characteristics of object-oriented: encapsulation, inheritance, polymorphism, (abstract)

3. Other keywords: this, super, static, final, abstract, interface, package, import

Process Oriented & Object Oriented

Process-oriented: The emphasis is on functional behavior, with functions as the smallest unit, and how to do it

Object-oriented: Emphasize objects with functions, take class/object as the smallest unit, and consider who will do it

An overview of object-oriented thinking

Two elements of object-oriented

**Class (Class)** is a description of a class of things, an abstract, conceptual definition

**Object (Object)** is each individual of this type of thing that actually exists, so it is also called an instance (instance)

A design class is a member of a design class

Members of a class (1-2): properties and methods

Common class members: attributes, behaviors (methods)

Attribute: member variable ------>field/domain, field

Method: member method ------> function (C language) ------> method

Three steps:
step1: create a class, design the members of the class
step2: create the object of the class
step3: call the structure of the object through "object.property" or "object.method"

class Person{
    
    
	
	//属性
	String name;
	int age;
	boolean isMale;
	//方法
	public void eat() {
    
    
		System.out.println("人可以吃饭");
	}
	public void sleep() {
    
    
		System.out.println("人可以睡觉");
	}
	public void talk(String language) {
    
    
		System.out.println("人可以说话,使用的是"+language);
	}
}

When we create a class, how do we use it - object: instantiation of java

/*类和对象的使用(面向对象思想落地的实现)
三步骤:
step1:创建类,设计类的成员
step2:创建类的对象
step3:通过“对象.属性”或“对象.方法”调用对象的结构
*/
public class personTest {
    
    
	public static void main(String[] args) {
    
    
		//创建person类的对象
		//step2:创建类的对象
		Person p1=new Person();
		//Scanner scanner=new Scanner(System.in)
		//调用对象的结构:属性、方法
		//step3:通过“对象.属性”或“对象.方法”调用对象的结构
		//调用属性:“对象.属性”
		p1.name="Tom";
		p1.isMale=true;
		System.out.println(p1.name);
	
		//调用方法:“对象.方法”
		p1.eat();
		p1.sleep();
		p1.talk("Chinese");
	}
}

//step1:创建类,设计类的成员
class Person{
    
    
	
	//属性
	String name;
	int age;
	boolean isMale;
	//方法
	public void eat() {
    
    
		System.out.println("人可以吃饭");
	}
	public void sleep() {
    
    
		System.out.println("人可以睡觉");
	}
	public void talk(String language) {
    
    
		System.out.println("人可以说话,使用的是"+language);
	}
}	

Now we create another object

Person p2=new Person();
System.out.println(p2.name);//Tom?   null? 
System.out.println(p2.isMale);//false
Person p3=p1;    //将p1变量保存的对象地址赋值给p3,导致p1和p3指向了堆空间中同一个对象实体
System.out.println(p3.name);//Tom

The result is null, what does this mean?

When we are new, we apply for a piece of memory space in the heap space: when we create multiple objects of a class, each object has an independent set of attributes of the class (non-static); this means: If we modify the property a of one object, it will not affect the value of property a of another object

Object memory parsing

image-20220918162528821

Use of attributes in classes

Properties (member variables) vs local variables

1. Similarities

​ 1.1 Define the format of variables: data type variable name = variable value

​ 1.2 Declare first, then use

1.3 Variables have their corresponding scope

2. Differences

​ 2.1 The positions declared in the class are different

​ Attribute: directly defined in a pair of {} of the class

​ Local variables: variables declared in methods, method parameters, code blocks, constructor parameters, and constructors

​ 2.2 Differences about modifiers

​ Attribute: You can specify its permissions when declaring attributes, using permission modifiers

​ Commonly used permission modifiers: private, public, default, protected—> encapsulation

​ At present, when you declare attributes, you can use the default

​ Local variables: permission modifiers are not allowed

​ 2.3 The case of default initialization value:

​ Attributes: The attributes of a class have default initialization values ​​​​according to their types (analogous to the initialization values ​​​​of one-dimensional array elements)

​ Integer (byte, short, int, long): 0

​ Floating point type (float, double): 0.0

​ Character type (char): 0

​ Boolean: false

​ Reference data type (class, array, interface): null

local variable: no default initialization value

​ means that we must assign a value before calling a local variable

​ In particular, the formal parameter can be assigned a value when it is called

2.4 Location loaded in memory:

Attribute: loaded into the heap space (non-static)

Local variables: loaded into stack space

package Class_and_Object;

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);
	}
}
class User{
    
    
	//属性
	String name;
	public int age;
	boolean isMale;
	//方法
	public void talk(String language) {
    
    
        //language是局部变量;这里可以在调用的时候赋值(因为是形参)
		System.out.println("我们使用"+language+"进行交流");
	}
	public void eat() {
    
    
		String food="米饭";//局部变量
		System.out.println("我们的主食是"+food);
	}
}

The use of methods in the class

Method: Describes the functionality a class should have

​ For example: Math class: sqrt() \random()...

1. Example:

class Customer{
    
    
	//属性
	String name;
	int age;
	boolean isMale;
	//方法
	public void eat() {
    
    
		System.out.println("客户吃饭");
	}
	public void sleep(int hour) {
    
    
		System.out.println("休息了:"+hour+"小时");
	}
	public String getName() {
    
    
		return name;
	}
	public String getNation(String nation) {
    
    
		String information="我的国籍是:"+nation;
		return information;
	}
}

The method used here is:

public void eat()

public void sleep(int hour)

public String getName()

public String getNation(String nation)

2. Declaration method:

Format:

权限修饰符 返回值类型 方法名(形参列表){    //形参列表根据实际情况不止一个
	方法体;
}  

3. Description

​ **3.1 Regarding permission modifiers: ** The permission modifiers of the default method first use public

java规定的四种权限修饰符:private、public、缺省、protected  ------>封装性

​ **3.2 Return value type: **With return value vs without return value

​ 3.2.1 If the method has a return value: it must be at the time of method declaration. Specify the type of the return value; at the same time, the method needs to use the return keyword to return the variable or constant of the specified type;

​ If the method has no return value: when the method is declared, use void to represent it. Usually, in a method without a return value, you do not need to use return; however, if you use return, it means the end of the method

​ 3.2.2 Should we have a return value when we define a method? Empiricism

​ **3.3 Method name: ** belongs to the identifier (see the name and meaning)

​ **3.4 Formal parameter list: **A method can declare 0, 1, or multiple formal parameters

格式:数据类型1 形参1,数据类型2 形参2,......

4. Use of the return keyword:

​ (1. Scope of use, used in the method body

(2. Function: end method;

​ For methods with return value types, use the "return data" method to return the required data

​ (3. Points to note: the execution statement cannot be declared after the return keyword

5. In the use of the method, you can call the properties or methods of the current class

​ [Special], method A is called again in method A: recursive method

​ In the method, the method cannot be defined

Example 1: Find the area of ​​a circle

public class CircleTest {
    
    
	public static void main(String[] args) {
    
    
		Circle c1=new Circle();
		c1.radius=2;
		double area=c1.findArea();
		System.out.println(area);
	}
}
class Circle{
    
    
	//属性
	double radius;       //半径
	//求圆的面积
	public double findArea() {
    
    
		double area=3.14*radius*radius;
		return area;
	}
}
public class Print_Matrix_class {
    
    
	public static void main(String[] args) {
    
    
		Print_Matrix_class test = new Print_Matrix_class();
		test.print_methed();
	}

//编写一个能打印*矩形的方法
	public void print_methed() {
    
    
		for (int i = 1; i <= 10; i++) {
    
    
			for (int j = 1; j <= 8; j++) {
    
    
				System.out.print("*");
			}
			System.out.println();
		}
	}
}

Pay attention to the inclusion relationship of the brackets. The print_methed() method is included in the public class class, which is equivalent to the large class of the entire file, so we still need to create an instantiated object when using the method: Print_Matrix_class test = new Print_Matrix_class(); test is the object we created

Example 2: Print a rectangle

public class Print_Matrix_class {
    
    
	public static void main(String[] args) {
    
    
		Print_Matrix_class test = new Print_Matrix_class();
		int area=test.print_methed();
		//方式1:
		System.out.println("面积为:"+area);
		//方式2:
		System.out.println(test.print_methed());
	}

//编写一个能打印*矩阵的方法
	public int print_methed() {
    
    
		for (int i = 1; i <= 10; i++) {
    
    
			for (int j = 1; j <= 8; j++) {
    
    
				System.out.print("*");
			}
			System.out.println();
		}
	//System.out.println(10*8);
		return 10*8;	
	}
}
System.out.println(test.print_methed());

For this statement, the output statement can also use [method] in brackets. Here, the method is regarded as a variable, and the value of the variable is the return value of the method (this type of calling method will not report an error)

public class Print_Rectangle_class02 {
    
    
	public static void main(String[] args) {
    
    
		Print_Rectangle_class02 test = new Print_Rectangle_class02();
		int result=test.method(5, 5);
		//方法1:
		System.out.println(result);
		//方法2:
		System.out.println(test.method(5, 5));
	}

	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();
		}
	return m*n;
	}
}

Example 3: Print student information

public class Students_class {
    
    
	public static void main(String[] args) {
    
    
		// 声明20个对象
		// student s1=new student(); //太多了
		// 声明student类型的数组
		student[] stu = new student[20]; // 对象数组

		for (int i = 0; i < 20; i++) {
    
    
			// 给数组元素赋值
			stu[i] = new student();
			// 给student对象属性赋值
			stu[i].number = i + 1;
			// 年级在1-6之间取随机数
			stu[i].state = (int) (Math.random() * (6 - 1 + 1) + 1);
			// 成绩在0-100范围
			stu[i].score = (int) (Math.random() * (100 - 0 + 1) + 1);
		}
		// 遍历学生数组
		for (int i = 0; i < stu.length; i++) {
    
    
			// System.out.println(stu[i]); 输出的结果为地址
			// 对于这类引用类型的变量,不是null那么就存地址
			// 这里因为stu已经new了,那么它就已经不是null了
			// 如果我们需要打印出值,我们需要引用它
			System.out.println(stu[i].number + "," + stu[i].state + "," +stu[i].score);
		}
		// 使用方法来实现
		// 方法1:
		for (int j = 0; j < stu.length; j++) {
    
    
			String info = stu[j].Studentinfo();
			System.out.println(info);
		}
		// 方法2:
		for (int j = 0; j < stu.length; j++) {
    
    
			System.out.println(stu[j].Studentinfo());
		}
		
		//打印出state3年级学生的成绩
		for (int j = 0; j < stu.length; j++) {
    
    
			if(stu[j].state==3) {
    
    
				System.out.println(stu[j].Studentinfo());
			}
		}
		//使用冒泡排序队学生成绩排序
		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) {
    
    
					student temp=stu[j];
					stu[j]=stu[j+1];
					stu[j+1]=temp;
				}
			}
		}
		for (int i = 0; i < stu.length; i++) {
    
    
			System.out.println(stu[i].number + "," + stu[i].state + "," +stu[i].score);
		}
	}
}

class student {
    
    
	// 属性
	int number; // 学号
	int state; // 年级
	int score; // 成绩
	// 方法
	// 显示学生信息
	public String Studentinfo() {
    
    
		return "学号" + number + "年级" + state + "成绩" + score;
	}
}

[Note]: What we need to pay attention to in bubble sorting is that when we define temporary variables, don't forget that the variable type is student

student temp=stu[j];

Then when exchanging, the wrong way of writing is:

student temp.score=stu[j];
stu[j].score=stu[j+1].score;
stu[j+1].score=temp;

Because if only the score is exchanged, then the student's grade is the grade of others, so what is exchanged is the entire attribute of the student

Example 4: Improvements to Example Three

Encapsulate the function of manipulating arrays into methods

public class Students_class02 {
    
    
	public static void main(String[] args) {
    
    
		// 声明20个对象
		// student s1=new student(); //太多了
		// 声明student类型的数组
		student1[] stu = new student1[20]; // 对象数组

		for (int i = 0; i < 20; i++) {
    
    
			// 给数组元素赋值
			stu[i] = new student1();
			// 给student对象属性赋值
			stu[i].number = i + 1;
			// 年级在1-6之间取随机数
			stu[i].state = (int) (Math.random() * (6 - 1 + 1) + 1);
			// 成绩在0-100范围
			stu[i].score = (int) (Math.random() * (100 - 0 + 1) + 1);
		}
		Students_class02 test=new Students_class02 ();     //在Students_class02 中造了方法,我们在使用前需要new一个对象
		test.traverse_print(stu);
		test.searchState(stu,6);
		test.sort(stu);
	}
	//遍历
	public void traverse_print(student1[] stu) {
    
    
		for (int i = 0; i < stu.length; i++) {
    
    
			System.out.println(stu[i].number + "," + stu[i].state + "," + stu[i].score);
		}
	}
	//选择年级
	public void searchState(student1[] stu, int state) {
    
    
		for (int j = 0; j < stu.length; j++) {
    
    
			if (stu[j].state == state) {
    
    
				System.out.println(stu[j].Studentinfo());
			}
		}
	}
	//按成绩排序
	public void sort(student1[] 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) {
    
    
					student1 temp = stu[j];
					stu[j] = stu[j + 1];
					stu[j + 1] = temp;
				}
			}
		}
	}
}
class student1 {
    
    
	// 属性
	int number; // 学号
	int state; // 年级
	int score; // 成绩
	// 方法
	// 显示学生信息
	public String Studentinfo() {
    
    
		return "学号" + number + "年级" + state + "成绩" + score;
	}	
}

Summary of object-oriented knowledge points

1. What are the three main lines of object-oriented thinking programming content

​ a. Classes and members of classes: properties, methods, constructors, code blocks, inner classes

b. Three major characteristics of object-oriented: encapsulation, inheritance, polymorphism

c. Other keywords: this, super, abstract, interface, static, final, package, import

Object-oriented programming ideas?

2. Understanding of classes and objects in object-oriented: Objects are instantiations of classes (objects are derived from class new)

​ Class: abstract, conceptual content

​ Object: a real individual (really occupying space in memory)

3. Three steps in the creation and execution of classes and objects

创建类------>类的实例化------>调用对象的结构:“对象.属性” “对象.方法”

4. Memory allocation

img

5. Process-oriented: functional behavior, with function as the smallest unit

​ Object-oriented: Emphasizes objects with functions

6. Memory Analysis Description

preson p1=new person();
preson p2=new person();
preson p3=p1;    //没有新建一个对象,共用一个堆空间

JVM (java virtual machine) memory structure

After compiling the source program, one or more bytecode files are generated, and we use the loader and interpreter of the JVM class to interpret and run the generated bytecode files. It means that the class corresponding to the bytecode file needs to be loaded into memory, which involves memory parsing

We load the new structure (for example: array, object) into the space. Supplement: Object properties (non-static) are loaded into the heap space

everything is an object

1. In the Java language category, we all encapsulate the functional structure into the class, and call the specific functional structure through the instantiation of the class

2. When it comes to the interaction between java language and front-end HTML and back-end database, when the front-end and back-end structures interact at the java level, they are all reflected in classes and objects

​ Scanner,String等

​ File, File

​ Web resource, URL

Memory parsing of object arrays

img

Use of anonymous objects

Code import:

public class Anonymous_Objects {
    
    
	public static void main(String[] args) {
    
    
		Phone p=new Phone();
		//p=null;
		System.out.println(p);    //带类型的地址
		p.playGame();
		p.sendEmail();  //有名字的对象:p(对象名)
		
		//匿名对象
		new Phone().sendEmail();
		new Phone().playGame();   //这两个用的就不是一个对象了(每new一个就是一个新对象)
		
		new Phone().price=1999;
		new Phone().showPrice();  //0.0(double类型,再次说明不是同一对象了)
	}
}
class Phone{
    
    
	double price;
	public void sendEmail() {
    
    
		System.out.println("发送邮件");
	}
	public void playGame() {
    
    
		System.out.println("玩游戏");
	}
	public void showPrice() {
    
    
		System.out.println(price);
	}
}

understand:

1. The object we created is assigned a variable name without display, which is an anonymous object

2. Features: Anonymous objects can only be called once

3. Use: as follows

class PhoneMall{
    
    
	public void showPhone(Phone iphone) {
    
      //
		iphone.sendEmail();
		iphone.playGame();
	}
}

PhoneMall p2=new PhoneMall();
p2.showPhone(new Phone());//匿名对象(new一个Phone类型的对象,只使用这一次)

Tool class for custom arrays

Through the above code, we have realized that the specific idea is encapsulated into the method. When we use it, we only need to call this method, which brings great convenience to our program, so we can try to put a part of the array Series methods are also wrapped into methods

//自定义数组工具类
public class Custom_Array_Tool_Class {
    
    
	// 求数组的最大值
	public int getMax(int[] arr) {
    
    
		int maxValue = arr[0];
		for (int i = 0; i < arr.length; i++) {
    
    
			if (maxValue < arr[i]) {
    
    
				maxValue = arr[i];
			}
		}
		return maxValue;
	}

	// 求数组的最小值
	public int getMin(int[] arr) {
    
    
		int minValue = arr[0];
		for (int i = 0; i < arr.length; i++) {
    
    
			if (minValue > arr[i]) {
    
    
				minValue = arr[i];
			}
		}
		return minValue;
	}

	// 求数组的总和
	public int getSum(int[] arr) {
    
    
		int sum = 0;
		for (int i = 0; i < arr.length; i++) {
    
    
			sum += arr[i];
		}
		return sum;
	}

	// 求数组的平均值
	public double getAverage(int[] arr) {
    
    
		int sum = 0;
		for (int i = 0; i < arr.length; i++) {
    
    
			sum += arr[i];
		}
		double averageValue = (sum * 1.0) / arr.length;
		return averageValue;
	}

	// 反转数组
	public void flipsArray(int[] arr) {
    
    
		for (int i = 0; i < arr.length / 2; i++) {
    
    
			int temp = arr[i];
			arr[i] = arr[arr.length - 1 - i];// 这里需要注意数组下标为arr.length-1代表的是最后一个元素
			arr[arr.length - 1 - i] = temp;
		}
	}

	// 复制数组
	public void copyArray(int[] arr) {
    
    
		int[] arr_copy = new int[arr.length];
		for (int i = 0; i < arr.length; i++) {
    
    
			arr_copy[i] = arr[i];
		}
	}

	// 数组排序
	public void sortArray(int[] arr) {
    
    
		for (int i = 0; i < arr.length; i++) {
    
    
			for (int j = 0; j < arr.length - 1 - i; j++) {
    
    
				if (arr[j] < arr[j + 1]) {
    
    
					int tem = arr[j];
					arr[j] = arr[j + 1];
					arr[j + 1] = tem;
				}
			}
		}
	}

	// 遍历数组
	public void throughArray(int[] arr) {
    
    
		for (int i = 0; i < arr.length; i++) {
    
    
			System.out.print(arr[i] + "\t");
		}
	}

	// 查找指定元素(线性查找)
	public int searchElement(int[] arr, int target) {
    
    
		for (int i = 0; i < arr.length; i++) {
    
            //这样就不用像之前那样再定义布尔变量啥的了
			if (target == arr[i]) {
    
    
				return i;
			}
		}
		return -1;//返回负数代表没找到
	}
}

Test: (using)

//使用我们自定义的数组工具Custom_Array_Tool_Class
public class Use_My_Arraytools {
	public static void main(String[] args) {
		
		Custom_Array_Tool_Class tool=new Custom_Array_Tool_Class();      //对象是类的实例化
		int[]arr=new int[]{32,45,67,44,-11,22,78,100,-56,-99,28};
		int max=tool.getMax(arr);
		System.out.println("最大值为:"+max);
		int min=tool.getMin(arr);
		System.out.println("最小值为:"+min);
		//等等
	}
}

Talking about methods again: method overloading

1. Concept: In the same class, more than one method with the same name is allowed, as long as their number of parameters or parameter types are different

​ Two identical and different: same class, same method name

​ The parameter list is different; the number of parameters is different; the parameter type is different

2. Example: overloaded sort()/binarySearch() in the Arrays class

​ Calling the System.out.println() method is an overload of the classic method

3. Determine whether to overload:

It has nothing to do with the method's permission modifier, return value type, formal parameter variable name, or method

4. When calling a method through an object, how to determine a specific method:

​ Method name ------> parameter list

Talking about methods again: variable number of formal parameters

1. New contents of jdk5.0

2. Specific use

2.1 format

public void show(String ... strs){
    
    
    System.outy.println("show(String ... strs)");
}

​ 2.2 When calling a variable number formal parameter method, the number of parameters passed in can be 0, 1, 2...

2.3 The method with variable number of formal parameters has the same name as the method in this class, and the methods with different formal parameters directly constitute overloading

​ 2.4 The method with the variable number of formal parameters has the same name as the original method, and the arrays with the same formal parameter types do not constitute refactoring (in other words: the two cannot coexist)

means that the two can replace each other

public void show(String ... strs){
    
    
    System.outy.println("show(String ... strs)");
}
public void show(String[] strs){
    
    
    System.outy.println("show(String ... strs)");
}

And when calling, the two can also represent each other

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

Therefore, we can understand that the system still regards a variable number of formal parameters as an array, but it is easier to write than an array

​ 2.5 The variable number of formal parameters must be declared at the end of the formal parameters of the method

public void show(int i,String ... strs);   //right
public void show(String ... strs,int i);   //wrong

​ 2.6 Variable number of formal parameters In the formal parameters of the method, at most one variable parameter can be declared

Talking about methods again: the value transfer mechanism of method parameters

variable assignment

public class Value_of_Method {
    
    
	public static void main(String[] args) {
    
    
		// 对于引用数据类型的值传递
		Order o1 = new Order();
		o1.OrderId = 1;
		Order o2 = o1;
		System.out.println("o1.OrderId=" + o1.OrderId + "\t" + "o2.OrderId=" + o2.OrderId);

		o2.OrderId = 2;
		System.out.println("o1.OrderId=" + o1.OrderId + "\t" + "o2.OrderId=" + o2.OrderId);
	}
}

class Order {
    
    
	int OrderId;
}

The result of the operation is as follows:

image-20220920160953365

Analysis: After assignment, for the reference data variable type , the address values ​​of o1 and o2 are the same, and both point to the same object entity in the heap space

Regarding variable assignment:

1. If the variable is a basic data type, the value assigned at this time is the data value saved by the variable

2. If the variable is a reference data type, the value assigned at this time is the address value of the data stored in the variable

Method parameter value transfer mechanism

1. Formal parameters: When the method is defined, the parameters in the declared parentheses

Actual parameter: the data actually passed to the formal parameter when the method is called

2. Value transfer mechanism

Introduce:

public class Value_Transfer02 {
    
    
	public static void main(String[] args) {
    
    
		int m=10;
		int n=20;
		System.out.println("m="+m+",n="+n);
		//交换两个变量
		//int temp=m;
		//m=n;
		//n=temp;
		//交换的操作很常用,我们不妨将此封装到方法中
		Value_Transfer02 useSwap=new Value_Transfer02();
		useSwap.Swap(m,n);
		System.out.println("m="+m+",n="+n);
	}
	
	public void Swap(int m,int n){
    
    
		int temp=m;
		m=n;
		n=temp;
	}
}

The result of the operation is as follows:

image-20220920162605973

We found that the purpose of our exchange was not achieved!

Understanding through memory:

img

Cause: If the parameter is a basic data type, what the actual parameter assigns to the formal parameter is the data value actually stored in the actual parameter

img

Therefore: if the variable is a reference data type, the address value of the data stored in the assigned variable at this time

Apply to arrays:

public class Arraysorting_class {
    
    
	public static void main(String[] args) {
    
    
		int[] arr=new int[] {
    
    -12,22,45,-87,-22,56,78,23,-66};
		Arraysorting_class arrnum=new Arraysorting_class();
		for(int i=0;i<arr.length;i++) {
    
    
			for(int j=0;j<arr.length-1-i;j++) {
    
    
				if(arr[j]<arr[j+1]) {
    
    
					arrnum.Swap(arr, i, j);
				}
			}
		}
		for(int i=0;i<arr.length;i++) {
    
    
			System.out.print(arr[i]+" ");
		}
	}
	public void Swap(int[] arr,int i,int j) {
    
    
		int tem=arr[j];
		arr[j]=arr[j+1];
		arr[j+1]=tem;
	}
}

[Summary]: Value transfer mechanism

​ If the parameter is a basic data type, what the actual parameter is assigned to the formal parameter at this time is the actual stored data value of the actual parameter

​ If the variable is a reference data type, the address value of the data saved by the assigned variable at this time

Example:

public class UseClass_Circle {
    
    
	//main方法
    public static void main(String[] args) {
    
    
		PassObject Use=new PassObject();
		Circle c=new Circle();
		Use.printAreas(c, 5);
		System.out.println("now radius is:"+c.radius);
	}
}
//输出半径和对应的圆面积
public class PassObject {
    
    

	public void printAreas(Circle c, int time) {
    
    //在这里已经定义了一个Circle类型的形参c了
		System.out.println("Radius\t\tArea");
		for (int i = 1; i <= time; i++) {
    
    
			c.radius = i;
			// 不用匿名对象
			double area = c.findArea();
			System.out.println(c.radius + "\t\t" + area);
			// 用匿名对象
			// System.out.println(c.radius + "\t\t" + c.findArea());
		}
		c.radius = time + 1;
	}
}
//Circle类
class Circle {
    
    
	double radius;

	public double findArea() {
    
    
		return 3.14 * radius * radius;
	}
}

Talking about methods again: the use of recursive methods

1. Recursive method: a method body calls itself

2. The recursion of the method contains an implicit loop, which will repeatedly execute a certain piece of code, but this repeated execution does not need to control the loop; the recursion must recurse in a known direction, otherwise this recursion becomes infinite recursion , similar to an infinite loop

Example 1: Summing

public class Recursion_Test {
    
    
	public static void main(String[] args) {
    
    
		//实例1:计算1-100所有自然数的和
		//循环
		int sum=0;
		for(int i=1;i<=100;i++) {
    
    
			sum+=i;
		}
		System.out.println(sum);
		Recursion_Test Test=new Recursion_Test();
		int Result=Test.getSum(100);
		System.out.println(Result);
		//System.out.println(Test.getSum(100));//匿名对象
	}
		
	
	//递归方法
	public int getSum(int n){
    
    //前n个数求和等于前n-1个数求和加上第n个数
		if(n==1) {
    
    
			return 1;
		}
		else {
    
    
			return n+getSum(n-1);
		}
	}
}

Similarly, we can write the calculation of the factorial of n

Example 2: Find factorial

public int getFactorial(int n){
    
    
		if(n==1) {
    
    
			return 1;
		}
		else {
    
    
			return n*getFactorial(n)
		}
	}
}

Example 3: Application

It is known that there is an array: f(0)=1, f(1)=4, f(n+2)=2*f(n+1)+f(n), where n is an integer greater than 0, find The value of f(10)

//已知有一个数组:f(0)=1,f(1)=4,f(n+2)=2*f(n+1)+f(n),其中n是大于0的整数,求f(10)的值
public class Recursion_Test2 {
    
    
	public static void main(String[] args) {
    
    
		Recursion_Test2 Use = new Recursion_Test2();
		int Result = Use.getNum(10);
		System.out.println(Result);
	}

	public int getNum(int n) {
    
    
		if (n == 0) {
    
    
			return 1;
		} else if (n == 1) {
    
    
			return 4;
		} else {
    
    
			return 2 * getNum(n - 1) + getNum(n - 2);
            // f(n+2)=2*f(n+1)+f(n)--->f(n)=2*f(n-1)+f(n-2)
		}
	}
}

Example 4: Fibonacci sequence

//斐波那契数列
public class Recursion_Test3 {
    
    
	public static void main(String[] args) {
    
    
		Recursion_Test3 Use=new Recursion_Test3();
		System.out.println(Use.Fibonacci(10));
	}
	public int Fibonacci(int n) {
    
    
		if(n==1) {
    
    
			return 1;
		}
		else if(n==2) {
    
    
			return 1;
		}
		else {
    
    
			return Fibonacci(n-1)+Fibonacci(n-2);
		}
	}
}

Periodic summary

1. What is method overloading?

​ Two identical and different: same class, same method name

​ The parameter list is different; the number of parameters is different; the parameter type is different

------> How to call a certain method: method name ------> parameter list

What is the difference between method overloading and overriding? : it doesn't matter

2. The continuation of the parameter passing mechanism in the java method

​ If the parameter is a basic data type, what the actual parameter is assigned to the formal parameter at this time is the actual stored data value of the actual parameter

​ If the variable is a reference data type, the address value of the data saved by the assigned variable at this time (including the data type of the variable)

3. Member variables and local variables

4. The use of the return keyword: the end method, for the method with a return value: return+return data

5. Memory structure: stack (local variable), heap (new structure: object (member variable), array)

Object-oriented feature one: encapsulation and hiding

The introduction of encapsulation

Our program design pursuit: "high cohesion, low coupling"

High cohesion: the internal data operation details of the class are completed by itself, and no external interference is allowed

Low coupling: only a small number of methods are exposed for use

Hide the internal complexity of the object and only expose a simple interface to the outside world. It is convenient for the outside world to call, hide what should be hidden, and expose what should be exposed. This is the encapsulation design idea

Introduction: When we create an object of a class, we can assign values ​​to the properties of the object through the method of "object.property". Here, the assignment operation is restricted by the data type and storage range of the attribute. In addition, there are no other constraints; but in practical problems, we often have to add additional constraints to attribute assignment. This condition cannot be reflected in the attribute declaration, we can only add restrictions through methods. (For example, setLegs, at the same time, we need to prevent users from assigning values ​​to properties in the way of "object.property". You need to declare the property as private (private), which reflects the encapsulation for the property .

public class Animal_Test {
    
    
	public static void main(String[] args) {
    
    
		Animal a=new Animal();
		a.name="Peter";
		a.age=2;
		a.setLegs(4);
		a.show();
		//a.legs=-4;    //虽然我们设计了方法setLegs能对输入的不合法数据进行辨析,但是我们							仍然能通过访问属性来修改legs的值
		//因此我们将属性legs设为一个私有属性:private,就不能在修改了
	}
}
class Animal{
    
    
	String name;
	int age;
	private int legs;  //腿的个数
	
	public void eat() {
    
    
		System.out.println("动物吃东西");
	}
	public void show() {
    
    
		System.out.println("name="+name+",age="+age+",legs="+legs);
	}
	//对属性的设置
	public void setLegs(int l) {
    
    
		if(l>=0&&l%2==0) {
    
    
			legs=l;
		}
		else {
    
    
			legs=0;
		}
	}
	//对属性的获取
	public int getLegs() {
    
    
		return legs;
	}
}

The embodiment of encapsulation

We privatize the properties of the class (private), and at the same time, provide public (public) methods to get (getXxx) and set (setXxx); in this case:

a.legs=4;     //wrong

Four Permission Modifiers

The embodiment of encapsulation requires permission modifiers to cooperate

1. The four kinds of permissions stipulated by java (arranged from small to large):

private、缺省、protected、public

Default means nothing is written

image-202209211352522252. Four permissions can modify the class and its internal structure: properties, methods, constructors, internal classes

3. Specifically, 4 kinds of permissions can be used to modify the internal structure of the class: attributes, methods, constructors, internal classes

If you modify the class, you can only use: default, public

Summary of encapsulation: Java provides four permission modifications to modify the class and its internal structure, reflecting the visibility of the class and its internal structure when it is called

Members of a class (3): Constructor

Any class has a constructor (Constructor)

The first two members of the class: properties and methods

The role of the constructor:

1. Create an object (new objects are connected to constructors)

2. Initialize the properties of the object

//创建对象
public class PersonTest {
    
    
	public static void main(String[] args) {
    
    
		//创建类的对象:new+构造器
		Person p=new Person();  //Person():构造器
		p.eat();
	}
}
class Person{
    
    
	//属性
    String name;
	int age;
	//方法
	public void eat() {
    
    
		System.out.println("人可以吃饭");
	}
	public void sleep() {
    
    
		System.out.println("人可以睡觉");
	}
}

illustrate

1. If there is no explicit definition of the constructor of the class, the system will provide a constructor with empty parameters by default

2. Define the format of the constructor:

权限修饰符 类名(形参列表){    //构造器名与类同名

}

class Person{
    
    
	//属性
    String name;
	int age;
	//构造器
    //作用1:创建对象
	public Person() {
    
    
		System.out.println("已被调用");
	}
    //作用2:给对象进行初始化
    public Person(String s){
    
    
        name=s;
    }
	//方法
	public void eat() {
    
    
		System.out.println("人可以吃饭");
	}
	public void sleep() {
    
    
		System.out.println("人可以睡觉");
	}
}

3. A class defines multiple constructors, which constitute overloads with each other

4. Once we show the constructor of the defined class, the system no longer provides the default empty parameter constructor

5. In a class, there will be at least one constructor (default/written by yourself)

Example: Triangle

public class TriangleTest {
    
    
	public static void main(String[] args) {
    
    
		Triangle t1=new Triangle();
		t1.setBase(2.0);
		t1.setHight(2.4);
		//t1.base=2.5;     wrong:private(存在但不可见)
		System.out.println("base:"+t1.getBase()+",hight:"+t1.getHight());
		//通过构造器的初始化
		Triangle t2=new Triangle(4.0,2.5);
		System.out.println("base:"+t2.getBase()+",hight:"+t2.getHight());
	}
}
public class Triangle {
    
    
	private double base;    //底
	private double hight;   //高
	
	//构造器
	public Triangle() {
    
    
		//空参
	}
	public Triangle(double b,double h) {
    
    
		base=b;
		hight=h;
	}
	
	public void setBase(double b) {
    
    
		base=b;
	}
	public double getBase() {
    
    
		return base;
	}
	public void setHight(double h) {
    
    
		hight=h;
	}
	public double getHight() {
    
    
		return hight;
	}
}

Summary: The sequential attributes of attribute assignment

1. Default initialization

2. Explicit initialization

3. Assignment in the constructor

4. Assignment through "object.method" (encapsulation) or "object.attribute"

The order of the above operations: 1------>2------>3------>4

javaBean

javaBean is a reusable component written in Java language

The so-called javaBean refers to a java class that meets the following standards:

类是公开的
一个无参的公共的构造器
有属性,且有对应的get、set方法
//javaBean
public class customer2 {
    
       //类是公开的
	private int id;
	private String name;

	public customer2() {
    
    
						   //一个无参的公共的构造器
	}
	//有属性,且有对应的get、set方法
	public void setId(int i) {
    
    
		id = i;
	}

	public int getId() {
    
    
		return id;
	}

	public void setName(String s) {
    
    
		name = s;
	}

	public String getname() {
    
    
		return name;
	}
}

Keyword: use of this

Use of the this keyword:

1.this can be used to modify: properties, methods, constructors

2.this is understood as: the current object

2.1 In the method of the class, we can use "this.property" or "this.method" to call the current object property or method. Usually, however, we choose to omit "this.". In special cases, if the formal parameter of the method has the same name as the attribute of the class, we must explicitly use the "this. variable" method, which means that the variable is an attribute, not a formal parameter

2.2 In the class constructor, we can use "this.property" or "this.method" to call the current object property or method. Usually, however, we choose to omit "this.". In special cases, if the formal parameter of the constructor has the same name as the attribute of the class, we must explicitly use the "this.variable" method, which means that the variable is an attribute, not a formal parameter

Example: account

public class Account {
    
    
	//属性
	private int id;     //账号
	private double balance; //余额
	private double annualInterestRate; //年利率
	//构造器
	public Account(int id,double balance,double annualInterestRate) {
    
    
		this.id=id;
		this.balance=balance;
		this.annualInterestRate=annualInterestRate;
	}
	//get/set方法:Source
	public int getId() {
    
    
		return id;
	}
	public void setId(int id) {
    
    
		this.id = id;
	}
	public double getBalance() {
    
    
		return balance;
	}
	public void setBalance(double balance) {
    
    
		this.balance = balance;
	}
	public double getAnnualInterestRate() {
    
    
		return annualInterestRate;
	}
	public void setAnnualInterestRate(double annualInterestRate) {
    
    
		this.annualInterestRate = annualInterestRate;
	}
	//取钱
	public void withdraw(double amount) {
    
    
		if(balance<amount) {
    
    
			System.out.println("余额不足");
		}
		else {
    
    
			System.out.println("成功取出"+amount+"元");
		}
	}
	public void deposit(double amount) {
    
    
		if(amount>0) {
    
    
			balance+=amount;
			System.out.println("成功存入:"+amount+"元");
		}
	}
}
public class Customer {
    
    
	private String firstName;
	private String lastName;
	private Account account;     //在属性中出现自定义类型的变量(引用数据类型)
	//构造器
	public Customer(String f,String l) {
    
    
		this.firstName=f;
		this.lastName=l;
	}
	//get-set
	public String getFirstName() {
    
    
		return firstName;
	}
	public void setFirstName(String firstName) {
    
    
		this.firstName = firstName;
	}
	public String getLastName() {
    
    
		return lastName;
	}
	public void setLastName(String lastName) {
    
    
		this.lastName = lastName;
	}
	public Account getAccount() {
    
    
		return account;
	}
	public void setAccount(Account account) {
    
    
		this.account = account;
	}
}
public class Test {
    
    
	public static void main(String[] args) {
    
    
		Customer c=new Customer("peter","smith");         //先实例化一个客户
		Account a=new Account(1000, 2000, 0.0123);        //再为它创建一个账户
		c.setAccount(a);                                  //这样这个账户就是这个客户的了    
		//可以连续.(访问)
		c.getAccount().deposit(100);   //存入100
		c.getAccount().withdraw(1000); //取出1000
		c.getAccount().withdraw(50);
	}
}

【Summarize】:

1. Association relationship: a variable of a custom type appears in the attribute (reference data type)

2. Object array (define multiple variables, input the reference type itself, or appear as an attribute)

3. Continuous operation

c.getAccount().deposit(100);  
c.getAccount().withdraw(1000); 
c.getAccount().withdraw(50);

Note that the previous method must have a return value, form a new object, and then call the next property or method

Keyword: use of package

1. In order to better realize the management of classes in the project, the concept of package is provided

2. Use package to declare the package to which the class or interface belongs, and declare it in the first line of the source file

image-20220926111314185

3. Packages, which belong to identifiers, follow the naming rules, specifications, and meanings of identifiers

4. Every time "." represents a layer of file directory

Supplement: Under the same package, interfaces and classes with the same name cannot be named

​ Under different packages, you can name interfaces and classes with the same name

Keyword: use of import

import: import

1. Explicitly use the import structure in the source file to import the classes and 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 structures, just write them out in parallel

4. "xxx.*" can be used to indicate that all structures under the xxx package can be imported

//并列写出
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
//或者:
import java.util.*;

5. If the class or interface used is defined under the java.lang package, the import structure can be omitted

6. If the class or interface used is defined under this package, the import structure can be omitted

7. If classes with the same name under different packages are used in the source file , at least one class must use the full class name explicitly

8. Use "xxx.*" to call all structures under the xxx package. But if you are using the structure under the xxx subpackage, you still need to explicitly import

9.import static: Import the static structure (attribute or method) in the specified class or interface

MVC design pattern

image-20220926115203778

Guess you like

Origin blog.csdn.net/kevvviinn/article/details/129420908