Java learning: object-oriented (1)

Fourth, object-oriented (1)

4.1 Process-oriented and object-oriented

Process Oriented (POP) vs. Object Oriented (OOP)

  • Both are a kind of thought, and object-oriented is relative to process-oriented. Process-oriented, the emphasis is onfunctional behavior, taking the function as the smallest unit, considerHow to do it. Object-oriented, encapsulating functions into objects, emphasizingFunctional object, taking class/object as the smallest unit, considerwho will do it
  • Object-oriented emphasizes the use of thinking methods and principles used by humans in daily thinking logic, such as abstraction, classification, inheritance, aggregation, polymorphism, etc.

Three characteristics of object-oriented

  • Encapsulation
  • Inheritance
  • Polymorphism

4.2 Basic Elements of the Java Language: Classes and Objects

Class (Class) and object (Object) are the core concepts of object-oriented.

  • A class is a description of a class of things, an abstract, conceptual definition
  • An object is each individual of this type of thing that actually exists, so it is also called an instance.
  • It can be understood as: class = abstract concept person; object = real person
  • The focus of object-oriented programming is
    the design of the class. The design of the class is actually the design of the members of the class.

Class Members
Common class members are:

  • Attribute: Member variable in the corresponding class
  • Behavior: the grammatical format of the member method class in the corresponding class
    insert image description here
修饰符 class 类名 {
    
    
	属性声明;
	方法声明;
}
说明:修饰符public:类可以被任意访问
		类的正文要用{
    
     }括起来

举例:
public class Person{
    
    
	private int age ; //声明私有变量 age
	public void showAge(int i) {
    
     //声明方法showAge( )
		age = i;
	}
}

4.3 Creation and use of objects

Create object syntax: class name object name = new class name ();
use " object name. object member " to access object members (including properties and methods).

举例:
public class Zoo{
    
    
	public static void main(String args[]){
    
    
		//创建对象
		Animal xb=new Animal();
		xb.legs=4;//访问属性
		System.out.println(xb.legs);
		xb.eat();//访问方法
		xb.move();//访问方法
	}
}

insert image description here

Exercise: Write a teacher class and a student class, and create objects through the test class for testing

//Student类
package demo04;

public class Student {
    
    
    private String name;
    private int age;
    private String major;
    private String interests;

    public Student(String name, int age, String major, String interests) {
    
    
        this.name = name;
        this.age = age;
        this.major = major;
        this.interests = interests;
    }

    public String getName() {
    
    
        return name;
    }

    public void setName(String name) {
    
    
        this.name = name;
    }

    public int getAge() {
    
    
        return age;
    }

    public void setAge(int age) {
    
    
        this.age = age;
    }

    public String getMajor() {
    
    
        return major;
    }

    public void setMajor(String major) {
    
    
        this.major = major;
    }

    public String getInterests() {
    
    
        return interests;
    }

    public void setInterests(String interests) {
    
    
        this.interests = interests;
    }
    public void study(){
    
    
        System.out.println("学生姓名:"+name);
        System.out.println("学生年龄:"+age);
        System.out.println("学科:"+major);
        System.out.println("兴趣:"+interests);
    }
}

//Teacher类
package demo04;

public class Teacher {
    
    
    private String name;
    private int age;
    private int teachAge;
    private String course;

    public Teacher(String name, int age, int teachAge, String course) {
    
    
        this.name = name;
        this.age = age;
        this.teachAge = teachAge;
        this.course = course;
    }

    public String getName() {
    
    
        return name;
    }

    public void setName(String name) {
    
    
        this.name = name;
    }

    public int getAge() {
    
    
        return age;
    }

    public void setAge(int age) {
    
    
        this.age = age;
    }

    public int getTeachAge() {
    
    
        return teachAge;
    }

    public void setTeachAge(int teachAge) {
    
    
        this.teachAge = teachAge;
    }

    public String getCourse() {
    
    
        return course;
    }

    public void setCourse(String course) {
    
    
        this.course = course;
    }
    public void teach(){
    
    
        System.out.println("教师姓名:"+name);
        System.out.println("教师年龄:"+age);
        System.out.println("教龄:"+teachAge);
        System.out.println("教授课程:"+course);
    }
}

//test类
package demo04;

public class test {
    
    
    public static void main(String[] args) {
    
    
        //教师类创建新对象
        Teacher teacher = new Teacher("李老师",35,10,"数学");
        teacher.teach();

        //学生类创建新对象
        Student student = new Student("田天赐",20,"Java","编程");
        student.study();
    }
}

->运行结果:
教师姓名:李老师
教师年龄:35
教龄:10
教授课程:数学
学生姓名:田天赐
学生年龄:20
学科:Java
兴趣:编程

Supplement: idea shortcut key

"Alt +" series

Alt + / Quick completion code (must be remembered, also the most commonly used)
Alt + Enter quick prompt completion, when there may be grammatical problems in the code, IDEA will prompt to use this shortcut key to quickly and automatically correct (very powerful, the most common Use)
Alt + insert to quickly generate constructors with arbitrary parameters, and Getter/Setter methods for private properties, etc. (most commonly used)
Alt+Q Display the declaration of the current method
Alt + 7 Quickly display the class structure, which can display the class contains All properties and methods of
Alt + left / right Quickly switch code view
Alt + Up / Down Quickly move and locate between methods (that is, the cursor moves in units of methods)

"Ctrl + "Series

Ctrl + W Select the text, press continuously to expand the selected range (in words)
Ctrl + Y Delete the current line
Ctrl + D Copy the current line, copy the current line directly in the next line (Duplicate copy)
Ctrl + / Add comments and cancel comments , [the first time is to add comments, the second time is to uncomment]
Ctrl + F to find text in the current file (Find search)
Ctrl + R to find and replace text (basically can complete the function of Ctrl + F), support multiple lines Find, or only find in the code, or only find in the comments, or use regular expressions to find (Replace replace)
Ctrl + O to quickly rewrite the method in the base class or interface (Override rewrite)
Ctrl + H to display the class structure Diagram (class inheritance hierarchy) (Hierarhcy level)
Ctrl + G Quickly navigate to the specified row and specified column
Ctrl + [ Quickly navigate to the beginning of the code block
Ctrl + ] Quickly navigate to the end of the code block
Ctrl + N Quickly search and open the class
Ctrl + B Quickly locate the source code, put the cursor on the method and enter, you can go to the source code of the method
Ctrl + U quickly go to the parent class of the current class

Combination key series

Ctrl + Alt + T Wrap the selected code with if, while, try/catch and other code blocks (powerful)
Ctrl + Alt + L Quickly format the code
Ctrl + Alt + I Auto-indent
Ctrl+Alt+O to optimize import classes and packages

4.4 One of the members of the class: attribute (field)

Grammar format : modifier data type attribute name = initialization value;

  • Note 1: Modifiers
    Commonly used permission modifiers are: private, default, protected, public
    Other modifiers: static, final (not considered yet)
  • Note 2: Data type
    Any basic data type (such as int, Boolean) or any reference data type.
  • Note 3: The attribute name
    is an identifier, and it only needs to conform to the naming rules and specifications.
举例:
public class Person{
    
    
	private int age; //声明private变量 age
	public String name =Lila; //声明public变量 name
}

Classification of variables: member variables and local variables

  • Outside the method body, the variables declared in the class body are called member variables.

  • Variables declared inside the method body are called local variables.
    insert image description here
    == Note ==: The similarities and differences between the two in terms of initialization values:

      同:都有生命周期
      异:局部变量除形参外,均需显式初始化。
    

The difference between member variables (attributes) and local variables:
insert image description here

4.5 The second member of the class: method (method)

  • A method is an abstraction of the behavioral characteristics of a class or object, and is used to complete a certain functional operation. Also known as a function or procedure in some languages.
  • The purpose of encapsulating functions as methods is to achieve code reuse and simplify code
  • Methods in Java cannot exist independently, all methods must be defined in the class.

Method declaration format:

修饰符 返回值类型 方法名(参数类型 形参1, 参数类型 形参2,.){
	方法体程序代码
	return 返回值;
}
其中:
修饰符:public,缺省,private, protected等
返回值类型:
>没有返回值:void>有返回值,声明出返回值的类型。与方法体中“return 返回值”搭配使用
方法名:属于标识符,命名时遵循标识符命名规则和规范,“见名知意”
形参列表:可以包含零个,一个或多个参数。多个参数时,中间用“,”隔开
返回值:方法在执行完毕后返还给调用它的程序的数据。
举例:
public class Person{
    
    
	private int age;
	public int getAge() {
    
     //声明方法getAge()
		return age; 
}
	public void setAge(int i) {
    
     //声明方法setAge
		age = i; //将参数i的值赋给类的成员变量age
	}
}

Classification of methods: according to whether there are formal parameters and return values

insert image description here
Notice:
(1) It must be declared first and then used, and the method must be defined inside the class
(2) It will be executed once it is called, and it will not be executed if it is not called.
(3) Methods or attributes in the class can be called in the method, and methods cannot be defined inside the method.

Correct example:

{
    
    
    方法1(){
    
    
        
    }
    方法2(){
    
    
        
    }
}

Error example:

{
    
    
    方法1(){
    
    
        方法2(){
    
      //位置错误
        
   		}
    }
}

4.5.1 Method overloading

The concept of overloading:
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.
Features of overloading:
It has nothing to do with the return value type, only look at the parameter list, and the parameter list must be different. (parameter number or parameter type). When calling, it is distinguished according to the method parameter list.
Overloaded method call : The JVM calls the matching method through the parameter list of the method.

First find the number and type that best match,
and then find the number and type that are compatible. If multiple methods are compatible at the same time, an error will be reported

Example of overloading :

//返回两个整数的和
int add(int x,int y){
    
    return x+y;}
//返回三个整数的和
int add(int x,int y,int z){
    
    return x+y+z;}
//返回两个小数的和
double add(double x,double y){
    
    return x+y;}
举例:
public class PrintStream {
    
    
	public static void print(int i) {
    
    ……}
	public static void print(float f) {
    
    ……}
	public static void print(String s) {
    
    ……}
	public static void main(String[] args) {
    
    
		print(3);
		print(1.2f);
		print("hello!");
	}
}

4.5.2 Value passing mechanism of method parameters

A method must be called by its class or object to be meaningful. If the method has parameters:

  • Formal parameter: the parameter when the method is declared
  • Actual parameter: The parameter value actually passed to the formal parameter when the method is called

How to pass the actual parameter value of Java into the method?

There is only one way to pass parameters to methods in Java: passing by value. That is, a copy (replica) of the actual parameter value is passed into the method, while the parameter itself is not affected.
The formal parameter is a basic data type: the actual parameter of the basic data type variable "data value"Pass to formal
parameter The formal parameter is a reference data type: the actual parameter reference data type variable"address value"passed to the parameter

练习:
1.定义一个int型的数组:int[] arr = new int[]{
    
    12,3,3,34,56,77,432};
让数组的每个位置上的值去除以首位置的元素,得到的结果,作为该位置上的新值。遍历新的数组
//正确写法1
for(int i = arr.length – 1;i >= 0;i--){
    
    
	arr[i] = arr[i] / arr[0];
}
//正确写法2
int temp = arr[0];
for(int i= 0;i < arr.length;i++){
    
    
	arr[i] = arr[i] / temp;
}

2.
int[] arr = new int[10];
System.out.println(arr);//地址值? [I@d716361
char[] arr1 = new char[10];
System.out.println(arr1); //地址值?           10个空值
3.1)定义一个Circle类,包含一个double型的radius属性代表圆的半径,一个findArea()方法返回圆的面积
(2)定义一个类PassObject,在类中定义一个方法printAreas(),该方法的定义如下:public void printAreas(Circle c, int time)在printAreas方法中打印输出1到time之间的每个整数半径值,以及对应的面积。例如,times为5,则输出半径12345,以及对应的圆面积。
(3)在main方法中调用printAreas()方法,调用完毕后输出当前半径值。

//Circle类
package demo05;

public class Circle {
    
    
    private double radius;

    public Circle(double radius) {
    
    
        this.radius = radius;
    }

    public double getRadius() {
    
    
        return radius;
    }

    public void setRadius(double radius) {
    
    
        this.radius = radius;
    }

    public double findArea(){
    
    
        return  radius*radius*Math.PI;

    }
}
//PassObject类
package demo05;

public class PassObject {
    
    
    public void printAreas(Circle c,int time){
    
    
        System.out.println("Radius\t\tArea");
        for (int i = 1;i <= time;i++) {
    
    
            c.setRadius(i);
            System.out.println(c.getRadius() + "\t\t" + c.findArea());
        }
    }
}

//Main类
package demo05;

public class Main {
    
    
    public static void main(String[] args) {
    
    
        PassObject passObject = new PassObject();
        Circle circle = new Circle(0);
        passObject.printAreas(circle, 5);
        System.out.println("nuw radius is: " + circle.getRadius());
    }
}

>运行结果
Radius		Area
1.0		3.141592653589793
2.0		12.566370614359172
3.0		28.274333882308138
4.0		50.26548245743669
5.0		78.53981633974483
nuw radius is: 5.0

4.5.3 Recursive methods

**Recursive method call:** The phenomenon that a method calls itself is called recursion.

Classification of recursion: direct recursion, indirect recursion.

  • Direct recursion: The method itself calls itself.

    public void methodA(){
          
          
    	methodA();
    }
    
  • Indirect recursion: It can be understood that the A() method calls the B() method, the B() method calls the C() method, and the C() method calls the A() method.


```java
  ```java
  public static void A(){
    
    
  	B();
  }
  
  public static void B(){
    
    
  	C();
  }
  
  public static void C(){
    
    
  	A();
  }

Description :

  • A recursive method contains one 隐式的循环.
  • A recursive method executes 重复执行a certain piece of code, but this repeated execution does not require a loop control.
  • Recursion must go to 已知方向recursion, otherwise this recursion becomes infinite recursion, which cannot be stopped, similar to 死循环. eventually happened 栈内存溢出.

Example 1: Calculate the sum of 1 ~ n
insert image description here
Example 2:
Calculate the nth value of the Fibonacci sequence (Fibonacci), the Fibonacci sequence satisfies the following rules,

1,1,2,3,5,8,13,21,34,55,....

That is, starting from the third number, a number is equal to the sum of the first two numbers. Suppose f(n) represents the nth value of the Fibonacci sequence, then f(n) satisfies: f(n)
= f(n-2) + f(n-1);

	//使用递归的写法
    int f(int n) {
    
    //计算斐波那契数列第n个值是多少
        if (n < 1) {
    
    //负数是返回特殊值1,表示不计算负数情况
            return 1;
        }
        if (n == 1 || n == 2) {
    
    
            return 1;
        }
        return f(n - 2) + f(n - 1);
    }

    //不用递归
    int fValue(int n) {
    
    //计算斐波那契数列第n个值是多少
        if (n < 1) {
    
    //负数是返回特殊值1,表示不计算负数情况
            return 1;
        }
        if (n == 1 || n == 2) {
    
    
            return 1;
        }
        //从第三个数开始,  等于 前两个整数相加
        int beforeBefore = 1; //相当于n=1时的值
        int before = 1;//相当于n=2时的值
        int current = beforeBefore + before; //相当于n=3的值
        //再完后
        for (int i = 4; i <= n; i++) {
    
    
            beforeBefore = before;
            before = current;
            current = beforeBefore + before;
            /*
            假设i=4
                beforeBefore = before; //相当于n=2时的值
                before = current; //相当于n=3的值
                current = beforeBefore + before; //相当于n = 4的值
            假设i=5
                beforeBefore = before; //相当于n=3的值
                before = current; //相当于n = 4的值
                current = beforeBefore + before; //相当于n = 5的值
                ....
             */
        }
        return current;
    }

4.6 Arrays of Objects

The elements of an array can be either primitive data types or reference data types. When the elements are classes in a reference type, we call it an array of objects.
example:

1.定义类Student,包含三个属性:学号number(int),年级state(int),成绩score(int)。 
创建20个学生对象,学号为120,年级和成绩都由随机数确定。
问题一:打印出3年级(state值为3)的学生信息。
问题二:使用冒泡排序按学生成绩排序,并遍历所有学生信息
提示:
1) 生成随机数:Math.random(),返回值类型double; 
2) 四舍五入取整:Math.round(double d),返回值类型long//Student类
public class Student {
    
    
	int number;//学号
	int state;//年级
	int score;//成绩		
	public void info(){
    
    
		System.out.println("number : " + number 
				+ ",state : " + state + ",score : " + score);
	}	
}
//StudentTest类
public class StudentTest {
    
    
    public static void main(String[] args) {
    
    
        // 数组的创建
        Student[] students = new Student[20];
        // 通过循环结构给数组的属性赋值
        for (int i = 0; i < students.length; i++) {
    
    
            // 数组元素的赋值
            students[i] = new Student();
            // 数组元素是一个对象,给对象的各个属性赋值
            students[i].number = (i + 1);
            students[i].state = (int) (Math.random() * 6 + 1);// [1,6]
            students[i].score = (int) (Math.random() * 101);// [0,100]
        }

        // 问题一:打印出3年级(state值为3)的学生信息。
        System.out.println("问题一:打印出3年级(state值为3)的学生信息。");
        for (int i = 0; i < students.length; i++) {
    
    
            if (students[i].state == 3) {
    
    
//				System.out.println(
//						"number:" + students[i].number + ",state:" + students[i].state + ",score:" + students[i].score);
                students[i].info();

            }

        }
        System.out.println("******************************");
        // 问题二:使用冒泡排序按学生成绩排序,并遍历所有学生信息
        // 排序前
        System.out.println("问题二:使用冒泡排序按学生成绩排序,并遍历所有学生信息");
        System.out.println("排序前");
        for (int i = 0; i < students.length; i++) {
    
    
//			System.out.println(
//					"number:" + students[i].number + ",state:" +
//							students[i].state + ",score:" + students[i].score);

            students[i].info();
        }

        System.out.println();
        // 排序:
        for (int i = 0; i < students.length - 1; i++) {
    
    
            for (int j = 0; j < students.length - 1 - i; j++) {
    
    
                if (students[j].score > students[j + 1].score) {
    
    
                    Student temp = students[j];
                    students[j] = students[j + 1];
                    students[j + 1] = temp;
                }
            }
        }

        // 排序后:
        System.out.println("排序后");
        for (int i = 0; i < students.length; i++) {
    
    
//			System.out.println(
//					"number:" + students[i].number + ",state:" +
//							students[i].state + ",score:" + students[i].score);

            students[i].info();
        }

    }

}

>运行结果:
问题一:打印出3年级(state值为3)的学生信息。
number : 1,state : 3,score : 98
number : 2,state : 3,score : 60
number : 5,state : 3,score : 71
number : 7,state : 3,score : 72
number : 8,state : 3,score : 72
number : 9,state : 3,score : 24
number : 14,state : 3,score : 0
number : 16,state : 3,score : 68
number : 18,state : 3,score : 29
number : 20,state : 3,score : 61
******************************
问题二:使用冒泡排序按学生成绩排序,并遍历所有学生信息
排序前
number : 1,state : 3,score : 98
number : 2,state : 3,score : 60
number : 3,state : 1,score : 22
number : 4,state : 6,score : 78
number : 5,state : 3,score : 71
number : 6,state : 5,score : 72
number : 7,state : 3,score : 72
number : 8,state : 3,score : 72
number : 9,state : 3,score : 24
number : 10,state : 1,score : 73
number : 11,state : 2,score : 0
number : 12,state : 2,score : 99
number : 13,state : 6,score : 65
number : 14,state : 3,score : 0
number : 15,state : 5,score : 61
number : 16,state : 3,score : 68
number : 17,state : 2,score : 41
number : 18,state : 3,score : 29
number : 19,state : 2,score : 14
number : 20,state : 3,score : 61

排序后
number : 11,state : 2,score : 0
number : 14,state : 3,score : 0
number : 19,state : 2,score : 14
number : 3,state : 1,score : 22
number : 9,state : 3,score : 24
number : 18,state : 3,score : 29
number : 17,state : 2,score : 41
number : 2,state : 3,score : 60
number : 15,state : 5,score : 61
number : 20,state : 3,score : 61
number : 13,state : 6,score : 65
number : 16,state : 3,score : 68
number : 5,state : 3,score : 71
number : 6,state : 5,score : 72
number : 7,state : 3,score : 72
number : 8,state : 3,score : 72
number : 10,state : 1,score : 73
number : 4,state : 6,score : 78
number : 1,state : 3,score : 98
number : 12,state : 2,score : 99

4.7 Keywords: package, import

4.7.1 package (package)

package, called a package, is used to indicate the package where the classes, interfaces, and other structures defined in the file are located.

package 顶层包名.子包名 ;

Example: pack1\pack2\PackageTest.java

package pack1.pack2;    //指定类PackageTest属于包pack1.pack2

public class PackageTest{
    
    
	public void display(){
    
    
		System.out.println("in  method display()");
	}
}

illustrate:

  • A source file can have only one package statement declaring a package
  • The package statement appears as the first statement in a Java source file. If this statement is defaulted, an unnamed package is specified.
  • Package name, which belongs to the identifier, meets the rules and specifications of identifier naming (all lowercase), sees the name
    • Packages usually use the inversion of the company's domain name, do not use " java.xx"package when taking the package name
  • The package corresponds to the directory of the file system, and "." is used in the package statement to indicate the level of the package (directory), and each time means a layer of file directory.
  • Multiple structures (classes, interfaces) can be declared under the same package, but structures (classes, interfaces) with the same name cannot be defined. Structures (classes, interfaces) with the same name can be defined under different packages

The role of the package

  • Packages can contain classes and subpackages, divided 项目层次for easy management
  • Help 管理大型软件system: divide classes with similar functions into the same package. For example: MVC design pattern
  • 类命名冲突problem solved
  • control访问权限

MVC design pattern

MVC is a software component pattern, the purpose is to reduce the coupling of code business in program development.

The MVC design pattern divides the entire program into three levels: 视图模型(Viewer)层, 控制器(Controller)层, and 数据模型(Model)层. This design pattern, which separates program input and output, data processing, and data display, makes the program structure flexible and clear. It also describes the communication method between various objects of the program, reducing the coupling of the program.

视图层viewer:显示数据,为用户提供使用界面,与用户直接进行交互。
 >相关工具类   view.utils
 >自定义view  view.ui

控制层controller:解析用户请求,处理业务逻辑,给予用户响应
 >应用界面相关    controller.activity
 >存放fragment   controller.fragment
 >显示列表的适配器 controller.adapter
 >服务相关的        controller.service
 >抽取的基类        controller.base
    
模型层model:主要承载数据、处理数据
 >数据对象封装 model.bean/domain
 >数据库操作类 model.dao
 >数据库      model.db

Main package introduction in JDK

java.lang---- Contains some core classes of the Java language, such as String, Math, Integer, System and Thread, providing common functions
java.net---- Contains classes and interfaces that perform network-related operations.
java.io---- Contains classes that can provide various input/output functions.
java.util---- Contains some utility classes, such as defining system characteristics, collection framework classes of interfaces, and using functions related to date and calendar.
java.text---- Contains some classes related to java formatting
java.sql---- Contains related classes/interfaces for JDBC database programming in java
java.awt---- Contains multiple classes that constitute the abstract window toolkits, These classes are used to build and manage the application's graphical user interface (GUI).

4.7.2 import (import)

In order to use Java classes defined in other packages, you need to use the import statement to explicitly introduce the classes required under the specified package. Equivalent to import语句告诉编译器到哪里去寻找这个类.

grammatical format

import 包名.类名;

Application examples

import pack1.pack2.Test;   //import pack1.pack2.*;表示引入pack1.pack2包中的所有结构

public class PackTest{
    
    
	public static void main(String args[]){
    
    
		Test t = new Test();          //Test类在pack1.pack2包中定义
		t.display();
	}
}

Precautions

  • The import statement, declared between the package declaration and the class declaration.

  • If you need to import multiple classes or interfaces, you can explicitly specify multiple import statements in parallel

  • If you use a.*the import structure, it means that you can import all the structures under the a package. Example: You can use java.util.* to import all classes or interfaces under the util package at one time.

  • If the imported class or interface is under the java.lang package, or under the current package, this import statement can be omitted.

  • If the classes under the java.a package have been imported, then if you need to use the classes under the sub-packages of the a package, you still need to import them.

  • If you use classes with the same name under different packages in your code, you need to use the full class name of the class to indicate which class is being called.

  • (Understanding) import staticthe use of combination: call the static property or method under the specified class or interface

4.8 Feature 1: encapsulation

The so-called encapsulation is to encapsulate objective things into classes of abstract concepts, and classes can only open their data and methods to trusted classes or objects, and hide information from unnecessary classes or objects.

In layman's terms, hide what should be hidden and expose what should be exposed. This is the design idea of ​​encapsulation.

Java implements data encapsulation

  • To achieve encapsulation is to control the scope of visibility of a class or member. This needs to be controlled by relying on access control modifiers, also known as permission modifiers.
  • Permission modifiers: public, protected, 缺省, private. The specific access scope is as follows:
Modifier Inside this class in this package Subclasses of other packages other package non-subclass
private × × ×
default × ×
protected ×
public
  • Specifically modified structure:
    • External class: public, default
    • Member variables, member methods, constructors, member inner classes: public, protected, default, private

4.8.1 Embodiment of encapsulation

Overview of member variable/property privatization
: privatize the member variables of the class, provide public get and set methods, and expose the function of obtaining and modifying properties.

Implementation steps:

Use privateto modify member variables

private 数据类型 变量名 ;

code show as below:

public class Person {
    
    
    private String name;
  	private int age;
    private boolean marry;
}

②Provide methods getXxx/ setXxxmethods to access member variables, the code is as follows:

public class Person {
    
    
    private String name;
  	private int age;
    private boolean marry;

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

    public String getName() {
    
    
        return name;
	}

    public void setAge(int a) {
    
    
        age = a;
    }

    public int getAge() {
    
    
        return age;
    }
    
    public void setMarry(boolean m){
    
    
        marry = m;
    }
    
    public boolean isMarry(){
    
    
        return marry;
    }
}

③Test :

public class PersonTest {
    
    
    public static void main(String[] args) {
    
    
        Person p = new Person();

        //实例变量私有化,跨类是无法直接使用的
		/* p.name = "张三";
        p.age = 23;
        p.marry = true;*/

        p.setName("张三");
        System.out.println("p.name = " + p.getName());

        p.setAge(23);
        System.out.println("p.age = " + p.getAge());

        p.setMarry(true);
        System.out.println("p.marry = " + p.isMarry());
    }
}

The benefits of member variable encapsulation:

  • Let the user only use the pre-determined method 访问数据, so that control logic can be added to the method to limit unreasonable access to member variables. Data inspection can also be performed to help ensure the integrity of object information.
  • 便于修改, improve code maintainability. The main thing is that the hidden part has been modified internally. If the external access method remains the same, the modification will not be felt externally at all. For example: Java8->Java9, String is converted from char[] to byte[] for internal implementation, but the external method remains unchanged, and our users can't feel its internal modification at all.

4.8.2 Privatization method

public class ArrayUtil {
    
    
	/**
	 * 
	 * @Description 求int型数组的最大值
	 * @param arr
	 * @return
	 */
	public int max(int[] arr) {
    
    
		int maxValue = arr[0];
		for(int i = 1;i < arr.length;i++){
    
    
			if(maxValue < arr[i]){
    
    
				maxValue = arr[i];
			}
		}
		return maxValue;
	}

	/**
	 * 
	 * @Description 求int型数组的最小值
	 * @param arr
	 * @return
	 */
	public int min(int[] arr){
    
    
		int minValue = arr[0];
		for(int i = 1;i < arr.length;i++){
    
    
			if(minValue > arr[i]){
    
    
				minValue = arr[i];
			}
		}
		return minValue;
	}

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

	/**
	 * 
	 * @Description 求int型数组的元素的平均值
	 * @param arr
	 * @return
	 */
	public int avg(int[] arr) {
    
    
		int sumValue = sum(arr);
		return sumValue / arr.length;
	}

	// 创建一系列重载的上述方法
	// public double max(double[] arr){}
	// public float max(float[] arr){}
	// public byte max(byte[] arr){}

	/**
	 * 
	 * @Description 遍历数组
	 * @param arr
	 */
	public void print(int[] arr) {
    
    
		for(int i = 0;i < arr.length;i++){
    
    
			System.out.print(arr[i] + "  ");
		}
		System.out.println();
	}

	/**
	 * 
	 * @Description 复制数组arr
	 * @param arr
	 * @return
	 */
	public int[] copy(int[] arr) {
    
    
		int[] arr1 = new int[arr.length];
		for(int i = 0;i < arr.length;i++){
    
    
			arr1[i] = arr[i];
		}
		return arr1;
	}

	/**
	 * 
	 * @Description 反转数组
	 * @param arr
	 */
	public void reverse(int[] arr) {
    
    
		for(int i = 0,j = arr.length - 1;i < j;i++,j--){
    
    
			int temp = arr[i];
			arr[i] = arr[j];
			arr[j] = temp;
		}
	}

	/**
	 * 
	 * @Description 数组的排序
	 * @param arr
	 * @param desc 指明排序的方式。 ascend:升序    descend:降序
	 */
	public void sort(int[] arr,String desc) {
    
    
		
		if("ascend".equals(desc)){
    
    //if(desc.equals("ascend")){
    
    
			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;
						swap(arr,j,j+1);
					}
				}
			}
		}else if ("descend".equals(desc)){
    
    
			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;
						swap(arr,j,j+1);
					}
				}
			}
		}else{
    
    
			System.out.println("您输入的排序方式有误!");
		}
	}
	
	private void swap(int[] arr,int i,int j){
    
    
		int temp = arr[i];
		arr[i] = arr[j];
		arr[j] = temp;
	}

	/**
	 * 
	 * @Description 查找指定的value值在arr数组中出现的位置
	 * @param arr
	 * @param value
	 * @return 返回value值出现的位置 或 -1:未找到
	 */
	public int getValue(int[] arr, int value) {
    
    
		//方法:线性查找
		for(int i = 0;i < arr.length;i++){
    
    
			if(value == arr[i]){
    
    
				return i;
			}
		}
		
		return - 1;
	}
}

Notice:

In development, general member instance variables are used to use private modification, and then provide corresponding public permission get/set method access.

For final instance variables, the set() method is not provided. (Speaking of the final keyword later)

For static final member variables, it is customary to use public modification.

4.9 The third member of the class: the constructor (Constructor)

The role of the constructor

new object, and assign values ​​​​to instance variables when new objects are created.

Example: Person p = new Person(“Peter”,15);

Explanation: Just as we stipulate that each "person" must take a bath as soon as he is born, we can add the program code to complete the "bath" in the constructor of the "person", so that each "person" will automatically complete the "bath" as soon as he is born. Take a bath" instead of telling each individual to "take a bath" one by one when they are newborns.

The syntax of the constructor

[修饰符] class 类名{
    
    
    [修饰符] 构造器名(){
    
    
    	// 实例初始化代码
    }
    [修饰符] 构造器名(参数列表){
    
    
        // 实例初始化代码
    }
}

illustrate:

  1. The constructor name must be the same as the class name in which it resides.
  2. It has no return value, so no return type is needed, nor void.
  3. The modifier of the constructor can only be a permission modifier and cannot be modified by any other. For example, it cannot be modified by static, final, synchronized, abstract, native, and cannot have a return statement return value.

code show as below:

public class Student {
    
    
    private String name;
    private int age;

    // 无参构造
    public Student() {
    
    }

    // 有参构造
    public Student(String n,int a) {
    
    
        name = n;
        age = a;
    }

    public String getName() {
    
    
        return name;
    }
    public void setName(String n) {
    
    
        name = n;
    }
    public int getAge() {
    
    
        return age;
    }
    public void setAge(int a) {
    
    
        age = a;
    }

    public String getInfo(){
    
    
        return "姓名:" + name +",年龄:" + age;
    }
}

public class TestStudent {
    
    
    public static void main(String[] args) {
    
    
        //调用无参构造创建学生对象
        Student s1 = new Student();

        //调用有参构造创建学生对象
        Student s2 = new Student("张三",23);

        System.out.println(s1.getInfo());
        System.out.println(s2.getInfo());
    }
}

Instructions for use

  1. When we do not explicitly declare the constructor in the class, the system will provide a parameterless constructor by default and the modifier of the constructor is the same as the modifier of the class by default.

  2. When we explicitly define the class constructor, the system no longer provides a default no-argument constructor.

  3. In a class, there will be at least one constructor.

  4. Constructors can be overloaded.

practise:

(1)定义Student,4个属性:
  String name; 
  int age; 
  String school; 
  String major;

(2)定义Student类的3个构造器:

- 第一个构造器Student(String n, int a)设置类的name和age属性;
- 第二个构造器Student(String n, int a, String s)设置类的name, age 和school属性;
- 第三个构造器Student(String n, int a, String s, String m)设置类的name, age ,school和major属性;

(3)在main方法中分别调用不同的构造器创建的对象,并输出其属性值。


public class Student {
    
    
    String name;
    int age;
    String school;
    String major;

    public Student(String n, int a) {
    
    
        name = n;
        age = a;
    }

    public Student(String n, int a, String s) {
    
    
        name = n;
        age = a;
        school = s;
    }

    public Student(String n, int a, String s, String m) {
    
    
        name = n;
        age = a;
        school = s;
        major = m;
    }

    public static void main(String[] args) {
    
    
        Student s1 = new Student("田大赐", 20);
        Student s2 = new Student("田二赐", 21, "北大");
        Student s3 = new Student("田三赐", 22, "清华", "Java");

        System.out.println(s1.name + " " + s1.age + " " + s1.school + " " + s1.major);
        System.out.println(s2.name + " " + s2.age + " " + s2.school + " " + s2.major);
        System.out.println(s3.name + " " + s3.age + " " + s3.school + " " + s3.major);
    }
}

>运行结果
田大赐 20 null null
田二赐 21 北大 null
田三赐 22 清华 Java

Guess you like

Origin blog.csdn.net/weixin_52357829/article/details/129761193