The article on object-oriented basis is enough ⭐ (recommended Collection)

The basic part of object-oriented has been sorted out, and the next part is intermediate and small project development
🔴🟢🟡

Classes and objects

A class is the template of an object, and an object is an individual of a class
Class is abstract and represents a class of things, such as human beings. It is a data type
The object is concrete and practical. It represents a specific thing and is an instance
Any class has member methods and member properties

Attribute / member variable / field

Conceptually or conceptually: member variable = attribute = field

  • The definition syntax of attributes is the same as that of variables
  • If the property is not assigned, it has a default value, and the rules are consistent with the array. Specifically: int 0, short 0, byte 0, long 0, float 0.0,double 0.0, char \u0000, boolean false, String null
  • An attribute is a component of a class. It is generally a basic data type or a reference type (object, array)

How to create objects

1 declare before creating

Cat cat ; //Declare object cat
cat = new Cat(); //establish

2 create directly

Cat cat = new Cat();

How to access properties

Basic syntax: object name Attribute name;

//Object name Attribute name;
cat.name ;
cat.color;

Memory allocation mechanism for classes and objects (important)

Structure analysis of Java Memory

  • Stack: general storage of basic data types (local variables)
  • Heap: storing objects
  • Method area: constant pool (constant, string), class loading information

  1. Load class information (properties and methods) first, and the information will be loaded only once
  2. Allocate space in the heap for default initialization
  3. Give an address to an object reference or object name
  4. Perform specified initialization
Person jack = new Person();
jack.age = 3;
Person tom;//Field pointer
tom = jack;//Give tom the address of the object jack, which is equivalent to one object and two references
System.out.println(tom.age);
System.out.println(jack.hashCode());//22307196
System.out.println(tom.hashCode());//22307196

Do a little exercise: define the Person class and instantiate the class

/**
 * @Author: liu sen
 * @Version: 1.0
 * @Date: 2021/09/01/10:26
 */
public class demo01 {
    public static void main(String[] args) {
        //Create a Person object, and jack is the object reference, or object name
        Person jack = new Person();
        System.out.println(jack.name);//The name of the output object jack. The String type is null by default
        System.out.println(jack.age);//The age of the output object jack. The int type is 0 by default
        System.out.println(jack.gender);//The gender of the output object jack, and the char type is null by default
    }
}
//Define a human being
class Person{
    String name;//full name
    int age;//Age
    char gender;//Gender
}

OK,Perfect

Method introduction

Methods are collections of statements that together perform a function

  • Method is an ordered combination of steps to solve a class of problems
  • Method is contained in a class or object
  • Methods are created in the program and referenced elsewhere

Principle of design method: the original intention of a method is a function block, which is a collection of statement blocks to realize a function. When designing a method, it is best to maintain the atomicity of the method. A method only completes one function, which is conducive to our later expansion.

Benefits of the method

This method can solve the problem of code redundancy and improve code reuse and maintainability

2. The implementation details can be encapsulated for other users to call

Definition of method

The access modifier returns the data type method name (formal parameter list)..) {//Method body
	sentence;
	return Return value;
}

be careful:

Formal parameter list: represents member method input
Return data type: indicates the member method output; void indicates no return value
The return statement is not required

Method invocation mechanism

  • When the program executes the method, it will open up an independent space (stack space)
  • When the method is executed, or when the return statement is executed, it will return to the place where it was called
  • After returning, continue to execute the following code until the main stack ends and is recycled, that is, the program ends

Method details

1. Access modifier
The function is to control the scope of use of the method

  • public
  • protected
  • default
  • private

2. Return data type
A method can have at most one return value. If you want to return multiple results, you can use arrays, objects

public class demo09 {
    public static void main(String[] args) {

        AA aa = new AA();
        int[] a = aa.getTwo(1,2);
        System.out.println(a[0]);
        System.out.println(a[1]);
    }
}
class AA{
    public int[] getTwo(int n1,int n2){
        int[] arr = new int[2];
        arr[0] = n1 + n2;
        arr[1] = n1 - n2;
        return arr;
    }
}
  • The return type can be any type, basic type and reference type (array, object)
  • If the method requires a return data type, the last execution statement in the method body must be a return value; Moreover, the return value type must be consistent or compatible with the return value type
  • If the method is void, there can be no return statement in the method body, or just write return;
  • The name of the method follows the hump naming method, and it is best to see the meaning of the name. In the actual development, the method is to realize some functions. According to the specification, it is best to see the meaning of the name

3. Formal parameter list

  • A method can have 0 parameters or multiple parameters, separated by commas
  • The parameter type can be any type, including basic type and reference type
  • When calling a method with parameters, you must pass in parameters of the same type or compatible type corresponding to the parameter list. Compatible type means that, for example, int type can be automatically transformed into double, which is the compatibility problem
  • The parameters when a method is defined become formal parameters. When a method is actually called, it is called an actual parameter, which is abbreviated as an argument. The types of arguments and formal parameters must be consistent or compatible, and the number and order must be consistent

4. Method body

Statement sets or statements that complete specific functions can be input, output, variables, operations, branches, loops, and method calls, but methods cannot be defined in methods, that is, methods cannot be nested

5. Method call

  • Method call of the same class: call directly
  • Cross class methods, class A calls class B methods: they need to be called through the object name. For example: object name Method name (parameter)
  • Cross class method calls are also related to the access modifier of the calling method

Method parameter transmission mechanism

Parameter transfer mechanism of basic data type
(for basic data type, the value (value copy) is passed, and any change of formal parameter will not affect the actual parameter!)

public class demo12 {
    public static void main(String[] args) {
        int a = 10;
        int b = 20;
        AA aa = new AA();
        aa.swap(a,b);
        System.out.println("a=" +a + "\t b=" +b);
    }
}
class AA{

    public void swap(int a,int b){
        System.out.println("a=" +a + "\t b=" +b);
        int temp = a;
        a = b;
        b = temp;
        System.out.println("a=" +a + "\t b=" +b);
    }
}

a=10	 b=20
a=20	 b=10
a=10	 b=20

Think, why output this?

First, there are two integers a and b in the main stack, 10 and 20 respectively. Then, a Class AA is instantiated to generate an object in the heap, called AA. The method in the class, swap, is called through the AA point. This will open up a new stack. Suppose it is called the swap stack. It is two independent spaces with the main stack. It executes methods and exchanges two numbers, At this time, the two numbers ab in the method are exchanged instead of ab in the main stack. After the method is executed, the swap stack is destroyed and recycled. The output statement is sandwiched. The output ab is in the main stack, so it is 10 and 20. The main stack is at the bottom of the stack. After the main stack is executed, the whole program is bound

Parameter passing mechanism of reference data type
(the reference type passes the address (the value is also passed, but the value is the address). You can affect the argument through formal parameters!)

public class demo13 {
    public static void main(String[] args) {

        B b = new B();
        int arr[] = {1,2,3};
        b.test(arr);
        System.out.println("===========");
        for (int i = 0; i < arr.length; i++) {
            System.out.println(arr[i]+"\t");
        }
    }
}
class B{
    public void test(int[] arr){
        arr[0] = 200;
        for (int i = 0; i < arr.length; i++) {
            System.out.println(arr[i]+"\t");
        }
    }
}

result:

200	
2	
3	
===========
200	
2	
3

analysis:

The main stack creates the object B in the heap, and then creates an array of reference types, which will also point to the heap space, with a size of 3, b.test(arr); Call method B to pass an array in and generate a new stack. Suppose it is called stack B. haha, copy the value of the reference type, and they point to the same array. At this time, the first element of the array is modified in the method, that is, modify the array at the same address, call the end, recycle stack B, return to the main stack, execute a for loop, and traverse the array, So in the end, 200, 2, 3 are output

Recursive mind method: from beginner to earth

Recursion is a method that calls itself,
Different variables are passed in each recursion,
Recursion helps programmers solve themselves,
Ha ha, I'm kidding. For complex problems,
At the same time, it can also make the code concise.

Important principles of recursion

  • When a method is executed, a new protected independent space (stack space) is created
  • The local variables of the method are independent and will not affect each other
  • If a reference type (such as an array) is used in a method, the data of that data type will be shared
  • Recursion must approach the condition of exiting recursion, otherwise infinite recursion will occur, dead turtle
  • When the method is executed or returns, 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 be executed

Recursive operation mechanism

Recursive factorial calculation

Calculate factorials using recursion

public class jie {
    public static void main(String[] args) {
        jie jie = new jie();
        System.out.println(jie.f(3));
    }
    public int f(int n){
        if(n == 1){
            return 1;
        }else {
            return n*f(n-1);
        }
    }
}

Recursive Fibonacci sequence

1, 1, 2, 3, 5, 8, 13... Give you an integer n and find out its value

Train of thought analysis:
When n = 1      1
 When n = 2		1
 When n >= 3		Sum of the first two numbers

public class feiBo {
    public static void main(String[] args) {
        T t = new T();
        int n = t.fei(-1);
        if(n != -1){
            System.out.println(n);
        }
    }
}
class T{
    public int fei(int n){
        if (n >= 1) {
            if(n == 1 || n == 2){
                return 1;
            }else{
                return fei(n-1) + fei(n-2);
            }
        }else {
            System.out.println("Incorrect input");
            return -1;
        }
    }
}

Recursive monkey eating peach problem

A pile of peaches. Monkeys ate half of them on the first day and ate one more. Later, monkeys ate half of them every day and then ate one more. When they wanted to eat again on the 10th day, they found that there was only one peach. Question: who is this monkey?

What are you looking at? It's you anyway. Ha ha, approve it. Question: how many peaches were there in the beginning?

Idea: reverse push
10			1
9		(1+1)*2=4
8		(((1+1)*2)+1)*2=10

Rule: Peaches the day before = (Peaches the next day+1)*2
public class houZi {
    public static void main(String[] args) {
        int day = 1;
        houZi houZi = new houZi();
        if(day != -1){
            System.out.println(houZi.peach(day));
        }

    }

    public int peach(int n){
        if(n == 10){
            return 1;
        }else if(n >= 1 && n <= 9){
            return (peach(n+1)+1)*2;
        }else {
            System.out.println("Input error");
            return -1;
        }
    }
}

Solving maze problem recursively

public class miGong {
    public static void main(String[] args) {
        //thinking
        //1. First create a maze and use a two-dimensional array to represent int[][] map = new int[8][7];
        //2. map: 0 indicates that you can walk, and 1 indicates that the wall cannot walk
        int[][] map = new int[8][7];
        for (int i = 0;i < 7;i++){
            map[0][i] = 1;
            map[7][i] = 1;
        }
        for (int i = 0;i < 8;i++){
            map[i][0] = 1;
            map[i][6] = 1;
        }
        map[3][1] = 1;
        map[3][2] = 1;
        //Print
        for (int i = 0; i < map.length; i++) {
            for (int j = 0; j < map[i].length; j++) {
                System.out.print(map[i][j]+" ");
            }
            System.out.println();
        }
        way f = new way();
        f.findWay(map,1,1);
        System.out.println("=====Find the way=====");
        for (int i = 0; i < map.length; i++) {
            for (int j = 0; j < map[i].length; j++) {
                System.out.print(map[i][j]+" ");
            }
            System.out.println();
        }
    }
}

class way{

    //Use the idea of recursive backtracking to solve
    public boolean findWay(int[][] map,int i,int j){
       if(map[6][5] == 2){
           return true;
       }else{
           if(map[i][j] == 0){
               //Suppose it can go through
               map[i][j] = 2;
               //Down right up left
               if(findWay(map,i+1,j)){//lower
                   return true;
               }else if(findWay(map,i,j+1)){//right
                   return true;
               }else if(findWay(map,i-1,j)){//upper
                   return true;
               }else if(findWay(map,i,j-1)){//Left
                   return true;
               }else {
                   map[i][j] = 3;
                   return false;
               }
           }else {
               return false;
           }
       }
    }
}

Method overload

In Java, multiple methods with the same name are allowed for the same class, but the formal parameter list is required to be inconsistent

Benefits:

  • Eased the trouble of naming
  • Eased the trouble of registration
public class demo01 {
    public static void main(String[] args) {
        System.out.println(1);
        System.out.println("asd");
        System.out.println('a');
    }
}

A name can output numbers, characters and strings, which is the so-called method overload

Source code:

Overload details

  • Method name: must be the same
  • Parameter list: must be the same (parameter type, number or order, at least one different, parameter name is not required)
  • Return type: no requirement

Variable parameters

java allows you to encapsulate multiple methods with the same name, the same function but different parameters in the same class into one method, which can be implemented through variable parameters

Basic grammar

Access modifier return type method name(Data type... Parameter name){
}

quick get start

public class demo04 {
    public static void main(String[] args) {
        demo04 demo04 = new demo04();
        System.out.println(demo04.sum(1,2,3,4,5,6,7,8,9,10));
    }
    public int sum(int n1,int n2){
        return n1+n2;
    }
    public int sum(int n1,int n2,int n3){
        return n1+n2+n3;
    }
    public int sum(int n1,int n2,int n3,int n4){
        return n1+n2+n3+n4;
    }
    //The names of the above three methods are the same, the functions are the same, and the number of parameters is different ---- variable parameter optimization is used
    //int... Indicates that variable parameters are accepted, and the type is int, that is, multiple ints can be accepted
    //You can use nums as an array
    //Traverse nums and sum
    public int sum(int... nums){
        int res = 0;
        for (int i = 0; i < nums.length; i++) {
            res += nums[i];
        }
        return res;
    }

}

matters needing attention:

  • The arguments of variable parameters can be any number or 0
  • Arguments to variable parameters can be arrays
  • The essence of variable parameters is arrays
public class demo05 {
    public static void main(String[] args) {
        int arr[] = {1,2,3};
        demo05 demo05 = new demo05();
        demo05.d(arr);
    }
    public void d(int... nums){
        System.out.println("length:" + nums.length);
    }
}

  • Variable parameters can be placed in the formal parameter list together with common type parameters, but it must be ensured that the variable parameters are at the end
public class demo05 {
    public static void main(String[] args) {
        demo05 demo05 = new demo05();
        demo05.f("Xiao Zhang",12,1.2);
    }

    public void f(String str,double... nums){
        System.out.println(str+"+"+nums.length);
    }
}

  • Only one variable parameter can appear in a formal parameter list

practice:

The three methods respectively realize the method of returning name and two course scores (total score), returning name and three course scores (total score), returning name and five course scores (total score), and encapsulating them into a variable parameter

public class demo06 {
    public static void main(String[] args) {
        demo06 demo06 = new demo06();
        System.out.println(demo06.fa("Xiao Zhang",100.3,123,12.9));
    }
    public double fa(String name,double... nums){
        double num1 = 0;
        System.out.println("name="+name);
        for (int i = 0; i < nums.length; i++) {
            num1+=nums[i];
        }
        return num1;
    }
}

Scope

In object-oriented, variable scope is a very important knowledge point

Scope: scope

  • In Java programming, the main variables are attributes (member variables) and local variables
  • Local variables generally refer to variables defined in member methods. For variables other than attributes, the scope is the scope of the code block that defines it
  • Global variables: attributes. The scope is the whole class. Global variables (attributes) can be used directly without assignment and have default values. Local variables can only be used after initialization. Local variables have no default values
public class demo07 {
    public static void main(String[] args) {

    }
    //Global variable: it is an attribute, and the scope is the whole class
    int age = 8;
    public void say(){
        //Local variables generally refer to variables defined in member methods
        //n and name are local variables
        //The scope of n and name is in the say method
        int n =10;
        String name = "xiao liu";
        System.out.println("age=" + age);
    }
}

Details:

  • Attributes and local variables can have the same name, and the principle of proximity shall be followed when accessing
class Person{
    String name = "jack";
    
    public void say(){
        String name = "king";
        System.out.println("name:" + name);//Can output king, proximity principle
    }
}

class Person{
    String name = "jack";

    public void say(){
//        String name = "king";
        System.out.println("name:" + name);//Can output king, proximity principle
    }
}

  • In the same scope, for example, in the same member method, two local variables cannot have the same name

  • The attribute declaration cycle is long. It is created with the creation of the object and destroyed with the destruction of the object. The local variable has a short life cycle. 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

  • Different scope of action:

  • Global variables / attributes can be called by this class or used by other classes (called through objects)

  • Local variables can only be used in the corresponding methods in this class

  • Modifier

  • Global variables / attributes can be modified

  • Local variables cannot be decorated

constructor

Requirements:

Before creating a human object, you first create an object and then assign a value to the human attribute. Now there is a need to directly specify the attribute value of the object when creating a human object. This requires the use of a constructor

public class demo08 {
    public static void main(String[] args) {
        //When we create a new object, we initialize it directly by specifying the property through the constructor
        Person person = new Person("Xiao Liu",8);
        System.out.println("name:"+person.name+"   Age:" + person.age);
    }
}

class Person{
    String name;
    int age;
    //constructor 
    public Person(String pName,int pAge){
        name = pName;
        age = pAge;
    }
}

Syntax:

Modifier method name (formal parameter list){
​		Method body;
}

be careful:

  • The modifier of the constructor can default
  • The constructor does not return a value, nor can void
  • Method name and class name must be the same
  • Parameter lists have the same rules as member methods
  • When creating an object, the system will automatically call the constructor of this class to complete the initialization of the object

Constructor: constructor

Constructor details

  • A class can define multiple constructors, that is, the constructor is overloaded, and there are two options when creating a new object
class Person{
    String name;
    int age;
    //constructor 
    public Person(String pName,int pAge){
        name = pName;
        age = pAge;
    }
    //Constructor Overload 
    public Person(String pName){
        name = pName;
    }
}

  • The constructor name is the same as the class name. If it is different, it is not a constructor. If it is not a constructor, it has a return value. If there is no return value, write void
  • Constructor has no return value
  • The constructor initializes the object, not creates it. When the constructor is called, the object already exists in the heap
  • When creating an object, the system automatically calls the constructor of this class
  • If the program element does not define a constructor, the system will automatically generate a default parameterless constructor for the class, such as Person {}
  • Once you define your own constructor, the default constructor will be overwritten and will not be added to you unless you show the definition, which is commonly used in development

Object creation process( ⭐)

class Person{
	int age = 90;
	String name;
	Person(String name,int a){
		name = n;
		age = a;
	}
}
Person p = new Person("xiao liu",2);
  1. Load the Person class information (Person.class) only once
  2. Allocate space (address) in heap
  3. Complete object initialization
    • Default initialization (age = 0; name = null;)
    • Explicit initialization (age = 90; name = null;)
    • Constructor initialization (age = 2; name = "xiao liu")
  4. Return the address of the object in the heap to p (object reference, object name)

Illustration:

this keyword

class Person{
    String name;
    int age;
    //constructor 
    public Person(String pName,int pAge){
        name = pName;
        age = pAge;
    }
}

The constructor parameter name is not very friendly. If you want to replace pName with name, try it

public class demo08 {
    public static void main(String[] args) {
        //When we create a new object, we initialize it directly by specifying the property through the constructor
        Person person = new Person("Xiao Liu",8);
        System.out.println("name:"+person.name+"   Age:" + person.age);
    }
}

class Person{
    String name;
    int age;
    //constructor 
    public Person(String pName,int pAge){
        name = pName;
        age = pAge;
    }
    //Constructor Overload 
    public Person(String pName){
        name = pName;
    }
}

Output:

After change:

public class demo08 {
    public static void main(String[] args) {
        //When we create a new object, we initialize it directly by specifying the property through the constructor
        Person person = new Person("Xiao Liu",8);
        System.out.println("name:"+person.name+"   Age:" + person.age);
    }
}

class Person{
    String name;
    int age;
    //constructor 
    public Person(String name,int age){
        name = name;
        age = age;
    }
    //Constructor Overload 
    public Person(String pName){
        name = pName;
    }
}

result:

According to the variable scope principle, the name of the constructor is a local variable, not an attribute. Similarly, age assigns its own value. The constructor is equivalent to invalid, so it will have default values of null and 0

Thinking: how to solve it?

Yes, this keyword is shining!!!

What is this

The java virtual opportunity assigns this to each object to represent the current object


For example, when each of us talks about ourselves, we say, mine. Different people say that the person represented is different. this refers to the attribute of the current object, nice

public class demo08 {
    public static void main(String[] args) {
        //When we create a new object, we initialize it directly by specifying the property through the constructor
        Person person = new Person("Xiao Liu",8);
        System.out.println("name:"+person.name+"   Age:" + person.age);
    }
}

class Person{
    String name;
    int age;
    //constructor 
    public Person(String name,int age){
        this.name = name;
        this.age = age;
    }
    //Constructor Overload 
    public Person(String pName){
        name = pName;
    }
}

result:

Advanced

this represents which object is called

Because Java runs on the virtual machine, there is no actual memory address, and only hashCode can simulate the address

Output the hashCode of the object and the hashCode of this to see if they are the same

public class demo08 {
    public static void main(String[] args) {
        //When we create a new object, we initialize it directly by specifying the property through the constructor
        Person person = new Person("Xiao Liu",8);
        System.out.println("name:"+person.name+"   Age:" + person.age);
        System.out.println(person.hashCode());

    }
}

class Person{
    String name;
    int age;
    //constructor 
    public Person(String name,int age){
        this.name = name;
        this.age = age;
        System.out.println(this.hashCode());
    }
    //Constructor Overload 
    public Person(String pName){
        name = pName;
    }
}


Beautiful

Keywords: Java OOP

Added by VinzC on Fri, 17 Dec 2021 16:26:13 +0200