Quick Start with Java—[Java Object-Oriented]—07

Object-oriented basics – Part 1

Today's content

  • object-oriented
  • Classes and Objects
  • Instance variables and instance methods

learning target

  • Able to understand object-oriented thinking
  • Able to clarify the relationship between classes and objects
  • Able to master the definition format of classes
    • Master the definition format of instance variables
    • Master the definition format of instance methods
  • Able to master the format of creating objects and access members in classes
    • Master accessing instance variables through objects
    • Master calling instance methods through objects

Chapter 5 Object-oriented thinking

5.1 Overview of object-oriented thinking

1 Overview

Java language is an object-oriented programming language, and object-oriented thinking (OOP) is a programming idea. Under the guidance of object-oriented thinking, we use Java language to design and develop computer programs. The objects
here generally refer to everything in reality, and each thing has its own attributes and behaviors . Object-oriented thinking is a design idea that refers to real things in the computer programming process, abstracts the attributes and behavioral characteristics of things, and describes them as computer events. It is different from process-oriented thinking (POP), which emphasizes on realizing functions by calling the behavior of objects, rather than operating and implementing them step by step.

2. The difference between object-oriented and process-oriented

Process-Oriented Programming: POP: Process-Oriented Programming

​ Taking function (method) as the smallest unit

Data is independent of functions

​ Focus on process and steps, and consider how to do it

Object Oriented Programming

Taking class/object as the smallest unit, class includes: data + method

​ Focus on the target (who), consider who will do it and who can do it

Object-oriented still includes process-oriented, but the focus has changed, focusing on who does it.

Programmer's role:

Process-oriented: programmers are the specific executors

Object-oriented: Programmers are commanders

Object-oriented thinking is a kind of thinking that is more in line with our thinking habits. It can simplify complex things and transform us from performers to commanders.

Example: Put the elephant in the refrigerator

Insert image description here

3. Basic characteristics of object-oriented

Object-oriented languages ​​contain three basic features, namely encapsulation, inheritance and polymorphism.

5.2 Classes and Objects

Look around and you will find many objects, such as tables, chairs, classmates, teachers, etc. Desks and chairs are office supplies, and teachers and students are human beings. So what is a class? What is an object?

what is class

  • Class : It is an abstract description of a class of things with the same characteristics, and is a set of related attributes and behaviors . It can be regarded as a template of a type of thing, and the attribute characteristics and behavioral characteristics of the thing are used to describe the type of thing.

In reality, describe a type of thing:

  • Attribute : It is the status information of the thing.
  • Behavior : What the thing can do.

Example: kitten.

Attributes: name, weight, age, color.
Behavior: Walking, running, barking.

what is object

  • Object : It is the specific embodiment of a type of thing. The object is an instance of the class (the object is not to find a girlfriend), and it must have the attributes and behaviors of that type of thing.

In reality, an instance of a class of things: a kitten.

Example: a kitten.

​ Attributes: tom, 5kg, 2 years, yellow.
​Behavior: Sliding along walls, running with bounding motion, and meowing.

The relationship between classes and objects

  • A class is a description of a type of thing and is abstract .
  • An object is an instance of a type of thing and is concrete .
  • A class is a template for an object, and an object is the entity of the class .

Insert image description here

5.3 Class definition and object creation

Contrast between things and classes

A class of things in the real world:

​Attributes : status information of things. Behavior
: What something can do.

The same is true for using classes to describe things in Java:

​Member variables : correspond to the attributes of things
​Member methods : correspond to the behaviors of things

Class definition format

public class ClassName {
    
    
  //成员变量
  //成员方法 
}
  • Define a class : Define the members of the class, including member variables and member methods .
  • Member variables : It is almost the same as defining variables before. Only the location has changed. In the class, outside the method .
  • Member method : The format is similar to the main method written before. It’s just that the functions and forms are richer. In the class, outside the method.

Example of class definition format:

public class Person {
    
    
  	//成员变量
  	String name;//姓名
    int age;//年龄
    boolean isMarried;
    
    public void walk(){
    
    
        System.out.println("人走路...");
    }
    public String display(){
    
    
        return "名字是:" + name + ",年龄是:" + age + ",Married:" + isMarried;
    }
}

Insert image description here

Creation of objects

Create object:

new 类名()//也称为匿名对象

//给创建的对象命名
//或者说,把创建的对象用一个引用数据类型的变量保存起来
类名 对象名 = new 类名();

Similar to:

System.out.println("柴老师年龄是:" + 18);//如果确定只在这里一次性使用,那么可以不用变量保存(#^.^#)

//把18用int类型的age变量保存起来,方便后面使用
int age = 18;
System.out.println("柴老师年龄是:" + age);
System.out.println("宋老师比柴老师大10岁,年龄是:" + (age+10));

So, what is stored in the object name? Answer: Object address

class Student{
    
    
    
}
public class TestStudent{
    
    
    //Java程序的入口
    public static void main(String[] args){
    
    
        System.out.println(new Student());//Student@7852e922
        Student stu = new Student();
        System.out.println(stu);//Student@4e25154f
        
        int[] arr = new int[5];
		System.out.println(arr);//[I@70dea4e
    }
}
//Student和TestStudent没有位置要求,谁在上面谁在下面都可以
//但是如果TestStudent类的main中使用了Student类,那么要求编译时,这个Student已经写好了,不写是不行的
//如果两个类都在一个.java源文件中,只能有一个类是public的

It is found that student objects are similar to array objects. Directly printing the object name and array name will display "type@object hashCode value", so classes and arrays are reference data types, and variables of reference data types store the address of the object. Or point to the first address of the object in the heap.

Insert image description here

5.4 Member variables

1. Classification of member variables

Instance variables: also called object attributes, belong to an object and are used through the object.

Class variables: Also called class variables, they belong to the entire class, not to a certain instance. This will be explained in the static section below.

2. How to declare instance variables?

【修饰符】 class 类名{
    
    
    【修饰符】 数据类型  属性名;    //属性有默认值
    【修饰符】 数据类型  属性名 =; //属性有初始值
}

Note: The type of attributes can be any type in Java, including basic data types, reference data types (classes, interfaces, arrays, etc.)

3. How to use instance variables?

(1) Instance variables are used directly in the instance methods of this class.

class Circle{
    
    
    double radius;
    
    public double getArea(){
    
    
        return 3.14 * radius * radius;
    }
}

(2) Instance variables need to be used in methods of other classes through the method of "object name.instance variable"

public class TestCircle{
    
    
	public static void main(String[] args){
    
    
		Circle c = new Circle();
		System.out.println("c这个圆的半径是:" + c.radius);
		
		//修改c这个圆的半径
		c.radius = 1.2;
		System.out.println("c这个圆的半径是:" + c.radius);
	}
}

4. Characteristics of instance variables

(1) Default value of member variable

basic type Integer (byte, short, int, long) 0
Floating point number (float, double) 0.0
character(char) ‘\u0000’
boolean false
type of data default value
reference type Array, class, interface null

(2) The value of instance variables is independent of each object

class Circle{
    
    
    double radius;
}
public class TestCircle{
    
    
	public static void main(String[] args){
    
    
		Circle c1 = new Circle();
		Circle c2 = new Circle();
		System.out.println("c1这个圆的半径是:" + c1.radius);//0.0
		System.out.println("c2这个圆的半径是:" + c2.radius);//0.0
		
		//修改c1这个圆的半径的值
		c1.radius = 1.2;
		System.out.println("c1这个圆的半径是:" + c1.radius);//1.2
		System.out.println("c2这个圆的半径是:" + c2.radius);//0.0		
	}
}

5. How to assign values ​​to instance variables?

(1) Explicitly assign a value when declaring a property. Then after each object is created, this property will not be the default value, but the initial value.

【修饰符】 class 类名{
    
    
    【修饰符】 数据类型  属性名 =; //属性有初始值
}

Code example:

class Student{
    
    
    String name;
    char gender = '男';//显式赋值
}

class TestStudent{
    
    
    public static void main(String[] args){
    
    
        Student s1 = new Student();
        System.out.println("姓名:" + s1.name);//null
        System.out.println("性别:" + s1.gender);//男
        
        s1.name = "小薇";//修改属性的默认值
        s1.gender = '女';//修改属性的初始值
        System.out.println("姓名:" + s1.name);//小薇
        System.out.println("性别:" + s1.gender);//女
        
        Student s2 = new Student();
        System.out.println("姓名:" + s2.name);//null
        System.out.println("性别:" + s2.gender);//男
    }
}

(2) Assign values ​​to attributes through objects

//为对象的属性赋值
对象名.属性名 =;

6. Instance variable memory map

class Student{
    
    
    String name;
    char gender = '男';//显式赋值
}
class TestStudent{
    
    
    public static void main(String[] args){
    
    
        Student s1 = new Student();
        System.out.println("姓名:" + s1.name);//null
        System.out.println("性别:" + s1.gender);//男
        
        s1.name = "小薇";
        s1.gender = '女';
        System.out.println("姓名:" + s1.name);//小薇
        System.out.println("性别:" + s1.gender);//女
        
        Student s2 = new Student();
        System.out.println("姓名:" + s2.name);//null
        System.out.println("性别:" + s2.gender);//男
    }
}

Insert image description here

7. The difference between instance variables and local variables

Variables have different names depending on where they are defined. As shown below:

  • Different positions in the class重点

    • Instance variables: in class, outside method

    • Local variables: in the method or on the method declaration (formal parameters)

      Insert image description here

  • The scope of action is different重点

    • Instance variables: used directly in the class, used by other classes through "object name.instance variable"
    • Local variables: in the scope of the current method
  • Difference in initialization values重点

    • Instance variables: have default values
    • Local variables: no default value. Must be defined first, assigned, and finally used
  • Different locations in memory了解

    • Instance variables: heap memory
    • Local variables: stack memory
  • different life cycles了解

    • Instance variables: exist when the object is created or the class is loaded, and disappear when the object disappears
      • In other words, without creating the object, its memory will not be allocated in the heap, create one, allocate one
    • Local variables: exist when the method is called and disappear when the method is called.
      • In other words, the method is not called, and the local variable does not allocate memory on the stack. It is called once and allocated once.

8. Practice with instance variables

Exercise 1: Declare the rectangle class

Requirements: Declare a rectangle class, including two instance variables of length and width, and create a rectangle object to find the area.

public class Field_Demo1 {
    
    
	public static void main(String[] args) {
    
    
		//创建对象
		Rectangle r = new Rectangle();
		r.length = 1;
		r.width = 2;
		System.out.println("长:" + r.length);
		System.out.println("宽:" + r.width);
		System.out.println("面积:" + r.length*r.width);
	}
}
class Rectangle{
    
    
	double length;
	double width;
}

Exercise 2: Declare the employee class

Requirements: Declare the employee class, including three instance variables: name, gender, and salary, create employee objects, and print information

public class Field_Demo2 {
    
    
	public static void main(String[] args) {
    
    
		//创建对象
		Employee emp = new Employee();
		emp.name = "柴林燕";
		emp.gender = '女';
		emp.salary = 10000;
		System.out.println("姓名:" + emp.name);
		System.out.println("性别:" + emp.gender);
		System.out.println("薪资:" + emp.salary);
	}
}
class Employee{
    
    
	String name;
	char gender;
	double salary;
}

Exercise 3: Declare Date Class

Requirements: Declare a date class, including three instance variables of year, month, and day, create a date object, and display information

public class Field_Demo3 {
    
    
	public static void main(String[] args) {
    
    
		//创建对象
		MyDate today = new MyDate();
		today.year = 2019;
		today.month = 7;
		today.day = 5;
		System.out.println("今天是" + today.year + "年" + today.month + "月" + today.day);
	}
}
class MyDate{
    
    
	int year;
	int month;
	int day;
}

Exercise 4: Declare the Husband and Wife classes

need:

Husband class: contains name and wife attributes

Wife class: contains name and husband attributes

Create a couple object and print information

public class Field_Demo4 {
    
    
	public static void main(String[] args) {
    
    
		//创建丈夫对象
		Husband husband = new Husband();
		//创建妻子对象
		Wife wife = new Wife();
		//指定属性
		husband.name = "邓超";
		wife.name = "孙俪";
		husband.wife = wife;
		wife.husband = husband;
		
		System.out.println("丈夫:" + husband.name + ",他妻子是:" + husband.wife.name);
		System.out.println("妻子:" + wife.name + ",他丈夫是:" + wife.husband.name);
	}
}
class Husband{
    
    
	String name;
	Wife wife;
}
class Wife{
    
    
	String name;
	Husband husband;
}

Insert image description here

5.5 Member methods

5.5.1 Concept of method

A method, also called a function, is the definition of an independent function and the most basic functional unit in a class.

The purpose of encapsulating a function into a method is to enable code reuse, thus reducing the amount of code.

5.5.2 Principles of method

Principles of using the method:

(1) Must be declared before use

Classes, variables, methods, etc. must be declared first and then used.

(2) It will not be executed if it is not called. It will be executed once it is called. Called once, a method stack is pushed onto the stack.

5.5.3 Classification of member methods

Member methods are divided into two categories:

  • Instance method: A method that belongs to an object and is called by the object.
  • Static method: Also called a class method, it belongs to the entire class, not to a certain instance. It is called by the class name. The static part will be explained later.

5.5.4 Detailed explanation of the format for defining instance methods

1. Grammar format

修饰符 返回值类型 方法名(【参数列表:参数类型1 参数名1,参数类型2 参数名, ......){
    
    
        方法体;return 返回值;}
  • Modifier: public is currently written in a fixed way, and no other modifiers have been learned.
  • Return value type: The data type that represents the result of the method execution. The result is returned to the caller after the method is executed.
    • Basic data types
    • Reference data type
    • No return value type: void
  • Method name: Give the method a name that can accurately represent the function of the method.
  • Parameter list: The method needs to use data from other methods internally. The data needs to be passed in the form of parameter transfer. It can be a basic data type, a reference data type, or it can have no parameters and write nothing.
  • Method body: specific function code
  • return: End the method and return the result of the method,
    • If the return value type is not void, there must be a return return value; statement in the method body, and the type of the return value result is required to be consistent or compatible with the declared return value type.
    • If the return value type is void, return does not need to be followed by a return value, or even no return statement.
    • No other code can be written after the return statement, otherwise an error will be reported: Unreachable code

2. The method declaration must be outside the method in the class

Correct example:

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

Error example:

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

5.5.5 Instance method call

  • Where the method is called: Called within another method.

    Correct example:

    {
          
          
        方法1(){
          
          
            调用其他方法;
        }
    }
    
  • Classification of method calls:

    • Called separately, the format is as follows:

      对象名.方法名(参数)
    • Output or return call, in the following format:

      System.out.println(对象名.方法名(参数));//直接输出方法调用后的返回值
      
      
      return 对象名.方法名(参数);//直接返回方法调用后的返回值作为当前方法的返回值
      
    • Assignment call, the format is as follows:

      数据类型 变量名 = 对象名.方法名(参数);
      

If the instance method is called from another instance method of this class, the "object name." can be omitted.

class Count {
    
    
    /*
    定义计算两个整数和的方法
    返回值类型,计算结果是int
    参数:不确定数据求和,定义int参数.参数又称为形式参数
    */
    public int getSum(int a, int b) {
    
    
        return a + b;
    }
    
    /*
    定义计算两个整数差的方法
    返回值类型,计算结果是int
    参数:不确定数据求差,定义int参数.参数又称为形式参数
    */
    public int getSubtract(int a, int b){
    
    
        return getSum(a,-b);//直接返回getSum(a,-b)方法调用的结果作为getSubtract(a,b)的结果
    }
}

public class Method_Demo1 {
    
    
    public static void main(String[] args) {
    
    
        // 创建对象
        Count c = new Count();
        
        // 通过单独调用方式调用方法
        c.getSum(3,4)
            
       	// 通过输出调用方式调用方法
        System.out.println(c.getSum(3,4));
        
        // 通过赋值调用方式调用方法
        int sum = c.getSum(3,4)System.out.println(sum);
    }
}
  • Formal parameters: When defining a method, the variable names in parentheses after the method name are called formal parameters (referred to as formal parameters), that is, formal parameters appear in the method definition.
  • Actual parameters: When calling another method in the caller method, the parameters in parentheses after the method name are called actual parameters (referred to as actual parameters), that is, the actual parameters appear in the caller method.

Summarize:

(1) When calling, you need to identify which method is called by the method name.

(2) When calling, you need to pass "actual parameters". The number, type, and sequence of actual parameters must correspond one-to-one with the formal parameter list.

​ If the method has no formal parameters, actual parameters are not needed and cannot be passed.

(3) When calling, if the method has a return value, the return value result can be accepted or processed.

​ If the return value type of the method is void, there is no need or ability to receive and process the return value result.

5.5.6 Defining and calling instance methods exercises

Exercise 1: Compare two integers to see if they are the same

  • Analysis: To define a method to implement a function, two clarifications are needed, namely 返回值and 参数列表.
    • Clear return value : comparing integers, there are only two possible comparison results, the same or different, so the result is of Boolean type, and the same comparison result is true.
    • Explicit parameter list : The two integers compared are uncertain, so two int type parameters are defined by default.
class Count {
    
    
    /*
        定义比较两个整数是否相同的方法
        返回值类型,比较的结果布尔类型
        参数:不确定参与比较的两个整数
    */
    public boolean compare(int a, int b) {
    
    
        if (a == b) {
    
    
            return true;
        } else {
    
    
            return false;
        }
    }
}

public class Method_Exer1 {
    
    
    public static void main(String[] args) {
    
    
        // 创建对象
        Count c = new Count();
        
        //调用方法compare,传递两个整数
        //并接收方法计算后的结果,布尔值
        boolean bool = c.compare(3, 8);
        System.out.println(bool);
    }
}

Exercise 2: Calculate the maximum value of two integers

  • Analysis: To define a method to implement a function, two clarifications are needed, namely 返回值and 参数列表.
    • Clear return value : compare integers, the result of the comparison is one of them, so it is int.
    • Explicit parameter list : The two integers compared are uncertain, so two int type parameters are defined by default.
class Count{
    
    
	public int max(int a,int b){
    
    
		return a>b?a:b;
	}
}
public class Method_Exer2{
    
    
	public static void main(String[] args) {
    
    
		java.util.Scanner input = new java.util.Scanner(System.in);
		System.out.print("请输入一个整数:");
		int x = input.nextInt();
		
		System.out.print("请输入另一个整数:");
		int y = input.nextInt();
		
		Count c = new Count();
		int max = c.max(x, y);
		System.out.println(x + "," + y + "中的最大值是:" + max);
	}
}

Exercise 3: Calculate the sum of 1+2+3…+100

  • Analysis: To define a method to implement a function, two clarifications are required, namely 返回值and 参数.
    • Clear return value : the sum of 1~100, it must still be an integer after calculation, the return value type is int
    • Clear parameters : The calculated data is known in the requirements, there is no unknown data, and no parameters are defined.
class Count {
    
    
	/*
        定义计算1~100的求和方法
        返回值类型,计算结果整数int
        参数:没有不确定数据
    */
    public int getSum() {
    
    
        //定义变量保存求和
        int sum = 0;
        //从1开始循环,到100结束
        for (int i = 1; i <= 100; i++) {
    
    
            sum = sum + i;
        }
        return sum;
    }
}

public class Method_Exer3 {
    
    
    public static void main(String[] args) {
    
    
        // 创建对象
        Count c = new Count();
        
        //调用方法getSum
        //并接收方法计算后的结果,整数
        int sum = c.getSum();
        System.out.println(sum);
    }
}

Exercise 4: Print HelloWorld an indefinite number of times

  • Analysis: To define a method to implement a function, two clarifications are required, namely 返回值and 参数.
    • Make the return value clearHelloWorld : just print it out in the method . There is no calculation result and the return value type void.
    • Clear parameters : it is not clear how many times to print, the parameter defines an integer parameter
class PrintUtil {
    
    
	/*
          定义打印HelloWorld方法
          返回值类型,计算没有结果 void
          参数:不确定打印几次
    */
    public void printHelloWorld(int n) {
    
    
        for (int i = 0; i < n; i++) {
    
    
            System.out.println("HelloWorld");
        }
    }
}

public class Method_Exer4 {
    
    
    public static void main(String[] args) {
    
    
        // 创建对象
        PrintUtil p = new PrintUtil();
        
        //调用方法printHelloWorld,传递整数
        p.printHelloWorld(9);
    }
}

Exercise 5: Realize printing of rectangular graphics with uncertain (number of rows, number of columns, and composed symbols)

  • Analysis: To define a method to implement a function, two clarifications are required, namely 返回值and 参数.
    • Make the return value clear : the method prints out a rectangle composed of sign in the line row and column column. There is no calculation result and the return value type void.
    • Clear parameters : how many lines and columns are printed, what symbols are composed is not clear, and the parameter defines three parameters
public class Method_Exer5 {
    
    
	public static void main(String[] args) {
    
    
		//创建对象
		PrintUtil pu = new PrintUtil();
		
		//调用printRectangle方法
		pu.printRectangle(5, 10, "&");
	}
}
class PrintUtil{
    
    
	public void printRectangle(int line, int column, String sign){
    
    
		for (int i = 0; i < line; i++) {
    
    
			for (int j = 0; j < column; j++) {
    
    
				System.out.print(sign);
			}
			System.out.println();
		}
	}
}

Exercise 6: Declare the circle class

  • Requirement: Declare a circle

    • Contains the instance variable radius to store the value of the radius of the circle object
    • Contains the instance method getArea to find the area of ​​a circle object
    • Contains the instance method getPerimeter to find the circumference of the circle object
    • Contains the instance method getInfo to obtain detailed information of the circle object
  • Analysis: To define a method to implement a function, two clarifications are required, namely 返回值and 参数.

    • Explicit return value :
      • The getArea() method needs to return the area value, so it is of double type
      • The getPerimeter() method needs to return the perimeter value, so it is of double type
      • The getInfo() method needs to return the complete information of the circle object, so it is of String type
    • Explicit parameters :
      • getArea() method, the area value can be calculated through the instance variable radius, so there is no need to design parameters.
      • getPerimeter() method, the perimeter can be calculated through the instance variable radius, so there is no need to design parameters.
      • The getInfo() method returns the complete information of the circle object, which consists of the value of the instance variable radius, the area value calculated by the getArea() method, and the circumference value calculated by the getPerimeter() method, so there is no need to design parameters.
public class Method_Exer6 {
    
    
	public static void main(String[] args) {
    
    
		//创建对象
		Circle c = new Circle();
		c.radius = 1.2;
		System.out.println(c.getInfo());
	}
}
class Circle{
    
    
	double radius;
	
	public double getArea(){
    
    
		return 3.14 * radius * radius;
	}
	
	public double getPerimeter(){
    
    
		return 2 * 3.14 * radius;
	}
	
	public String getInfo(){
    
    
		return "半径:" + radius + ",面积:" + getArea() + ",周长:" + getPerimeter();
	}
}

Exercise 7: Declare the customer, account class, and bank class

  • Declare account class Account

    • Contains: two instance variables: account and balance
    • Contains save deposit method
    • Contains withdraw withdrawal method
  • Declare the customer class Customer

    • Contains: name and mobile phone, ID number, an account owned, and four instance variables
  • Declare the bank class BankClerk

    • Contains the open method to open an account for a customer object and associate the information of the Customer and Account objects.
class Account{
    
    
	String id;
	double balance;
	public void save(double money){
    
    
		if(money > 0){
    
    
			balance += money;
		}else{
    
    
			System.out.println("参数有误");
		}
	}
	public void withdraw(double money){
    
    
		if(money <0){
    
    
			System.out.println("参数有误");
		}else if(money > balance){
    
    
			System.out.println("余额不足");
		}else{
    
    
			balance -= money;
		}
	}
}
class Customer{
    
    
	String name;
	String tel;
	String cid;
	Account account;
}
class BankClerk{
    
    
	public void open(Customer c, Account a){
    
    
		c.account = a;
	}
}
public class Method_Exer6 {
    
    
	public static void main(String[] args) {
    
    
		//创建客户对象
		Customer c = new Customer();
		c.name = "柴林燕";
		c.tel = "10086";
		c.cid = "111111111111111111";
		
		//创建银行卡账号对象
		Account a = new Account();
		a.id = "12345678910";
		a.balance = 0;
		
		//银行对象
		BankClerk b = new BankClerk();
		b.open(c, a);
		System.out.println("姓名:" + c.name + ",电话:" + c.tel + ",身份证号:" + c.cid + ",账号:" + c.account.id + ",余额:" + c.account.balance);
		
		//存款
		c.account.save(1000);
		System.out.println("姓名:" + c.name + ",电话:" + c.tel + ",身份证号:" + c.cid + ",账号:" + c.account.id + ",余额:" + c.account.balance);
		
		//取款
		c.account.withdraw(2000);
		//显示信息
		System.out.println("姓名:" + c.name + ",电话:" + c.tel + ",身份证号:" + c.cid + ",账号:" + c.account.id + ",余额:" + c.account.balance);
	}
}

5.5.7 Method call memory analysis

The method will not be executed if it is not called. It will be executed once when it is called. Each call will have a push action on the stack, that is, an independent memory area will be opened for the current method to store the value of the local variable of the current method. When the method execution ends After that, the memory will be released, which is called popping the stack. If the method has a return value, the result will be returned to the calling place. If there is no return value, it will end directly and return to the calling place to continue executing the next instruction.

Stack structure: first in, last out, last in, first out.

class Test18_Invoke_Memory{
    
    
	public static void main(String[] args){
    
    
		Count c = new Count();
		
		int x = 1;
		int y = 2;
		
		int sum = c.getSum(x,y);
		System.out.println(x + " + " + y + " = " + sum);
	}
}
class Count{
    
    
	public int getSum(int a, int b){
    
    
		return a + b;
	}
}

Insert image description here

Guess you like

Origin blog.csdn.net/weixin_42258633/article/details/125663608