Java Note 6 object oriented programming (elementary)

Posted by deived on Mon, 07 Mar 2022 15:56:33 +0100

6.1 class and object

  • A class is a data type
  • An object is a concrete instance
  • If the attribute (member variable) is not assigned a value, it has a default value, and the rules are consistent with the array

6.2 existence form of object in memory

6.3 memory allocation mechanism of classes and objects

6.4 method calling mechanism and principle

6.5 member method and parameter transmission mechanism

6.5.1 parameter transmission mechanism of basic data type

  • The basic data type passes the value (one copy), and the change of formal parameter does not affect the actual parameter

6.5.2 parameter transfer mechanism of reference data type

  • The reference data type passes the address, and the argument can be affected by formal parameters

  • p=null; And p=new Pewson(); Is to change the address P in the stack space opened by the method, and the address P in the main stack and the memory pointed to by the address will not be affected

Exercise 6.5

Write a method copyPerson, which can copy a Person object and return the copied object. When cloning an object, note that the new object and the original object are two independent objects, but their properties are the same

6.6 method recursive call

6.6.1 recursive cases

public class Recursion01 {
    //Write a main method
    public static void main(String[] args) {
        T t1 = new T();
        t1.test(4);//Output what? n=2 n=3 n=4
        int res = t1.factorial(5);
        System.out.println("5 factorial  res =" + res);
    }
}
class T {
    //Print problem
    public void test(int n) {
        if (n > 2) {
            test(n - 1);
        }
        System.out.println("n=" + n);
	}
    //factorial
    public int factorial(int n) {
        if (n == 1) {
            return 1;
        } else {
            return factorial(n - 1) * n;
		}
	}
}

6.6.1.1 printing problems

6.6.1.2 factorial problem

6.6.2 important recursive rules

  1. When a method is executed, a new protected independent space (stack space) is created
  2. The local variables of the method are independent and will not affect each other, such as n variables
  3. If a reference type variable (such as array or object) is used in the method, the data of the reference type will be shared
  4. Recursion must approach the condition of exiting recursion, otherwise it is infinite recursion. StackOverflowError appears and the turtle is dead
  5. When a method is executed or encounters a return, it will return. The result will be returned to the person who calls it. At the same time, when the method is executed or returned, the method will also be executed, releasing the control right of stack space and the allocation right of data

6.6.3 practice

  1. public class RecursionExer01 {
        public static void main(String[] args) {
            T t1 = new T();
            System.out.println(t1.fibonacci(7));
        }
    }
    
    class T {
        /*
        n = 1 Fibonacci number - > 1
        n = 2 Fibonacci number - > 1
        n >= 3 Fibonacci number - > sum of the first two numbers
         */
        public int fibonacci(int n) {
            if(n >= 1){
                if(n == 1 || n == 2)
                    return 1;
                else
                    return fibonacci(n-1) + fibonacci(n-2);
            }else{
                System.out.println("Please enter an integer greater than one!");
                return -1;
            }
            
        }
    }
    
  2. /*
    Monkeys eat more than half a peach at a time, and there is one left on the tenth day. How many were there originally
     Backstepping:
    day = 10 There is a peach
    day = 9 When (day10+1) * 2 = 4
    day = 8 When (day9+1) * 2 = 10
    ......
     */
    public class RecursionExer02 {
        public static void main(String[] args) {
            T t1 = new T();
            System.out.println(t1.eatPeach(8));
        }
    }
    class T {
        public int eatPeach(int day) {
            if(day == 10) {
                return 1;
            } else if (day >= 1 && day <= 9){
                return (eatPeach(day + 1) + 1) * 2;
            } else {
                System.out.println("Input 1-10");
                return -1;
                
            }
        }
    }
    

6.6.4 maze

See code migong java

6.6.5 tower of Hanoi

6.6.6 eight queens

6.7 method overload

Different parameters (number, type and order) with the same name, and the return type is not required

public int calculate(int n1, int n2) {
	System.out.println("calculate(int n1, int n2) Called");
	return n1 + n2;
}
//There is no method overload, which is still wrong because it is a duplicate definition of the method
//public void calculate(int n1, int n2) {
//	System.out.println("calculate(int n1, int n2) is called");
//	int res = n1 + n2;
//}

6.8 variable parameters

6.8.1 concept and usage

java allows you to encapsulate multiple methods with the same name and function but different parameters in the same class into one method.

public int sum(int... nums) {
	//System.out.println("number of parameters received =" + num.length ");
	int res = 0;
	for(int i = 0; i < nums.length; i++) {
		res += nums[i];
	}
	return res;
}

int res = sum(1, 2);
int res = sum(1, 2, 3);

6.8.2 use details

  1. The arguments of variable parameters can be 0 or any number of arguments
  2. The argument of a variable parameter can be an array
  3. The essence of variable parameters is arrays
  4. Variable parameters can be placed in the parameter list together with ordinary parameters, but it must be ensured that the variable parameters are at the end
  5. Only one variable parameter can appear in a parameter list

6.8.3 practice

public class VarParameterExercise {
    public static void main(String[] args) {
        HspMethod hsp = new HspMethod();
        System.out.println(hsp.showScore("Li Ming", 85, 90, 94));
        System.out.println(hsp.showScore("Zhang Hua", 70, 85, 75, 60));
    }
}

class HspMethod {
    public String showScore(String name, double... scores) {
        double sum = 0;
        for (int i = 0; i < scores.length; i++) {
            sum += scores[i];
        }
        return name + scores.length + "The total score of the course is:" + sum;
    }
}

6.9 scope

6.9.1 basic use

  1. In Java programming, the main variables are attributes (member variables) and local variables
  2. Local variables are generally variables defined in value member methods and variables defined in code blocks
  3. Classification of scopes
    1. Global variable: that is, attribute, whose scope is the whole class body (member methods can be used directly)
    2. Local variable: a variable other than an attribute whose scope is in the code block that defines it
  4. Global variables can be used directly without assignment, because they have default values; Local variables must be assigned before they can be used because there is no default value

6.9.2 use details

  1. Attributes and local variables can have the same name and follow the principle of proximity when accessing
  2. Two local variables cannot have the same name in the same scope
  3. The attribute life cycle is long, which is created with the creation of the object and destroyed with the destruction of the object; The life cycle of a local variable is short. It is created with the execution of its code block and destroyed with the end of the code block, that is, in the process of a method call
  4. Different scope of action
    1. Global variable / attribute: it can be used by this class or other classes (called through objects)
    2. Local variable: can only be used in the corresponding method in this class
  5. Different modifiers
    1. Global variables / attributes can be modified
    2. Local variables cannot be decorated

6.10 construction method / constructor

Complete initialization of object

6.10.1 basic grammar

[Modifier ] Method name (parameter list ) {
    Method body;
}

6.10.2 use details

  1. The modifier of the constructor can be default, public, protected or private
  2. Constructor has no return value
  3. The method name is consistent with the class name (case)
  4. The parameter list is consistent with the rules of the member method (it can have no parameters, multiple parameters or all parameters)
  5. The constructor is called by the system. When creating an object, the system will automatically call the constructor of this class to complete the initialization of the object
  6. When there is no constructor defined, the system will automatically generate a parameterless constructor
  7. After you define your own constructor, the default constructor is overwritten, and you can no longer use the default parameterless constructor, unless you explicitly define it, that is: Dog() {}

6.11 process analysis of object creation

class Person {
    int age = 90;
    String name;
    Person(String n, int a) {
        name = n;
        age = a;
    }
}

Person p = new Person("Xiao Qian", 20);

technological process:

  1. Loading Person class information (Person.class) will only load once
  2. Allocate space (address) in heap
  3. Complete object initialization
    1. The default initialization rule is consistent with the array
    2. Explicit initialization, age = 90, name = null
    3. Constructor initialization, age = 20, name = "Xiaoqian"
  4. Return the address of the object in the heap to p (p is the object name, which can also be understood as the reference of the object)

6.12 this keyword

  1. Which object is called, this represents which object

  2. This keyword can be used to access the properties, methods and constructors of this class

    1. Syntax for accessing member methods: this Method name (parameter list);

    2. Access constructor syntax: this (parameter list); Note that it can only be used in the constructor (that is, it can only access another constructor in the constructor, which must be placed in the first statement)

      1. class T {
            private String name;
            private int age;
            //this access constructor example
            public T() {
                this("jack", 100);
                System.out.println("T()Constructor called");
            }
            public T(String name, int age) {
                System.out.println("T(String name, int age)Constructor called");
                
            }
            //Example of this access member method
            public void f1() {
                System.out.println("f1()method···");
            }
            public void f2() {
                System.out.println("f2()method···");
                f1();	//Call the first method of f1 of this class
                this.f1();	//The second method of calling f1 of this class is different
            }
        }
        
  3. this is used to distinguish between the properties and local variables of the current class

  4. this cannot be used outside the class definition, but only in the method defined by the class

Topics: Java