The first step of object-oriented in Java is to polish the foundation

Posted by Darkmatter5 on Thu, 10 Feb 2022 10:13:36 +0100

A program is a world with many things (objects [properties, behaviors])

Classes and objects

Class represents a common product and a comprehensive feature, while the object is a product of personality and an individual's sign

A class is a template of an object. An object is an individual of a class, corresponding to an instance

Class is abstract and represents a class of things, such as humans and cats

The object is concrete and practical. It represents a specific thing, that is, an instance

A class can only be used through an object, and all operations of the object are defined in the class.

Class consists of properties and methods:

**Attribute (member variable): * * is equivalent to human characteristics, such as eyes, mouth and nose

Member variable = attribute = field

An attribute is a component of a class. It is generally a basic data type or a reference type (object, array).

**Method (behavior)** It is equivalent to human behavior, such as talking, farting, sleeping and singing

If the class is instantiated, it must rely on the object and must be in the main method

Class name object name = new class name ();

cat cat1 = new cat();

Illustration above

At present, there are several kinds of cats Create object 2 Instantiate an object 3 Instantiate a class

The biggest feature of Java is object-oriented

Object memory layout

**Stack: * * the instruction area of java stores program instructions, defined constants and variables of fixed length. Advantages: access speed is faster than heap, second only to register

Stack data can be shared; Disadvantages: the data size and life cycle in the stack must be determined, which is lack of flexibility.

**Heap: * * the data area of java is a runtime data area from which class objects allocate space. They do not need the release of program code display, but are responsible by the garbage collection mechanism. The advantage is that the memory address can be allocated dynamically, and the lifetime does not need to be told to the compilation area in advance, because it allocates memory dynamically at runtime. java has an automatic garbage collection system to automatically collect data that is no longer used** Disadvantages: * * due to the dynamic allocation of memory at runtime, the access speed is slow

It can be seen that the reference variables in the stack memory do not really store the variable data in the object. The variable data of the object is actually placed in the heap memory, and the reference variables only point to the objects in the heap memory.

Attribute considerations and details

1. The definition syntax of attributes is the same as that of variables, such as access modifier attribute type attribute name;

2. The definition type of attribute can be any type, including basic type or reference type

3. If the attribute is not assigned a value, 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,char \u0000,

boolean false,String null;

Access properties

Basic grammar

Object name Attribute name;

Object allocation mechanism

Memory allocation mechanism of classes and objects

Analysis of java memory structure

1. Stack: general storage of basic data types (local variables)

2. Heap: store objects (cat array, etc.)

3. Method area: constant pool (constant, such as string), class loading information

4. Schematic diagram [Cat(name,age,price)]

Simple analysis of the process of creating objects in Java

Person p = new Person();

p.name = "jack";

p.age = 10;

1. Load the Person class information first (attribute and method information, which will only be loaded once)

2. Allocate space in the heap for default initialization (see the rules)

3. Point the address p to the object

4. Perform specified initialization, such as p.name = "jack" p.age = 10

Create object process
public class Person01 {
    public static void main(String[] args) {
        //Create Person object
        //p1 is the object name (object reference)
        //The object space (data) created by new Person() is the real object
        Person  p1 = new Person();
        System.out.println(p1.age);
        System.out.println(p1.name);
        System.out.println(p1.sal);
        System.out.println(p1.isPass);
        
    }
}
class Person{
        //Four attributes
    int age;
    String name;
    double sal;
    boolean isPass;
}

Member method (behavior for short)

Basic introduction

In some cases, we need to define member methods, such as humans: in addition to some attributes (age, name), we humans also have some behaviors, such as

Talk, run, study and make friends. Now we can do it with the member method

Public means public void: means the method has no return value. speak():speak method name, () parameter list

The {} method body can write the code we want to execute

System.out.println("I am a good man");

Our method is output

in a word

classPerson{
	public  void  speak(){

    ​		System.out.println("I am a good man");

    }
} 
Method use
class Test{
    public static void main(String[] args){
        Person p1 = newPerson;
        p1.speak();
        p1.call();
    }
}
public void call(){

​		int res  = 0;

​		for(int i = 1; i<=1000;i++){
			res+= i;
		}
		System.out.println("Calculation results="+res);

}
Formal parameter usage
public int getsum(int num1,int num2){
    int res = num1 + num2;
    return res;
}
public static void main(String[] args){
//Call getsum method, and num1 = 10; num2 = 20
//Assign the value returned by getsum to the variable returnRes
int returnRes = p1.getsum(10,20);
}

Definition of member method

public returns the data type method name (parameter table...) {/ / method body

Statement;

Return return value;

Return type considerations and details

1. A method can have at most one return value [thinking, how to return multiple results?]

2. The return type can be any type, including basic type or reference type (array, object)

3. If the method requires a return value 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

4. If the method is void, the method body can have no return statement or write only return;

Precautions and usage details of parameter list

1. A method can have multiple 0 parameters or multiple parameters, separated by commas. getSum(int n1,int n2)

2. The parameter type can be any type, including basic type or reference type. printArr(int[ ,][, ] map )

3. When calling a parameter method, you must pass in parameters of the same type or compatible type [getSum] corresponding to the parameter list

4. The parameters during method definition are called formal parameters, which are called formal parameters for short; The parameters when a method is called are called actual parameters, which are abbreviated as actual parameters. The types of actual parameters and formal parameters

To be consistent or compatible, the number and order must be consistent!

Method body

The specific statements of the completed functions can be input, output, variables, operations, branches, loops and method calls, but they can't

Redefine the method! That is: methods cannot be nested.

Method invocation considerations and usage details

1. Description of method call in the same class: call directly. For example, print (parameter);

2. Class A method in cross class calls class B method: it needs to be called through object name.

3. Cross class method calls are related to method access modifiers.

Method call details

1. When the program executes the method, it will open up an independent space (stack space)

2. When the method is executed or the return statement is executed, it will return

3. Return to the place where the call was sent

4. After returning, continue to execute the code behind the method

5. When the main method (stack) is executed, the whole program exits

Method parameter transmission mechanism

1. Parameter transmission mechanism of basic data type

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

2. Conclusion

Basic data type. The value passed is (value copy). Any change of formal parameter will not affect the actual parameter!

2. Reference type parameter transfer mechanism

public class Method {
    public static void main(String[] args) {
        //test
        B b= new B();
        int[] arr = {1,2,3};
        b.test100(arr);
        System.out.println("main of arr array");
        //Traversal array
        for (int i= 0; i< arr.length;i++){
            System.out.println(arr[i]);
        }

    }
}
class B{
    public void test100(int[] arr){
        arr[0] = 200;//Modify element
        // Traversing the array of B
        for (int i = 0;i< arr.length;i++){
            System.out.print(arr[i]+"\t");
        }
    }
}

Look at the case. Class B writes a method test100, which can receive an array. Modify the array in the method. Is the original array OK

Change

2. Conclusion

The reference type passes the address (the value is also passed, but the value is the address), and the argument can be affected by formal parameters.

Method recursion

Basic introduction

To put it simply: recursion is a method that calls itself and passes in different variables each time; Help programmers solve complex problems and make the code concise

What problems can recursion solve?

1. Various mathematical problems: such as 8 queen problem, Hanoi Tower, factorial problem, maze, ball and basket

2. Recursion will also be used in various algorithms, such as fast sorting, merge sorting, binary search and divide and conquer algorithms

3. The problem to be solved with stack - "recursive code" is relatively simple

Recursive call mechanism diagram

public class jicheng1 {
    public static void main(String[] args) {
            o o1 = new o();
            o1.test(4);
    }
}
class o {
    public void test(int n) {
        if (n > 1) {
            test(n - 1);
        }
        System.out.println("n=" + n);
    }
}

public class jicheng1 {
    public static void main(String[] args) {
            o o1 = new o();
           int res =  o1.fact(5);
           System.out.println("res="+res);
    }
}
class o {
    public int fact(int n){
        if (n==1){
            return 1;
        }else{
            return fact(n-1)*n;
        }
    }
}
Recursive considerations and instructions

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

2. If a reference variable (such as an array) 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

5. When a method is executed or returns, it will return. The result will be returned to the person who calls it. When the method is executed or returned at the same time, the method will also be executed.

Method overloading

Basic introduction

Java allows the existence of multiple methods with the same name in the same class, but requires inconsistent formal parameter lists

benefit

1. Ease the trouble of naming 2 Registered trouble

Use details

1. Method name: must be the same

2. Parameter list: must be different (parameter type or number or order, at least one different, parameter name is not required)

3. Return type: no requirement

public class zaiOne {
    public static void main(String[] args) {
        Methods rn = new Methods();
        System.out.println(rn.max(95,100));
        System.out.println(rn.max(25.1,26.3));
        System.out.println(rn.max(25.1,26.3,85.2));
    }
}
class Methods{
    public int max(int n1,int n2){
        return n1>n2?n1:n2;
    }
    public double max(double n1,double n2){
        return n1>n2?n1:n2;
    }
    public double max(double n1,double n2,double n3){
        double max1 = n1>n2?n1:n2;
        return max1>n3?max1:n3;
    }
}

Variable parameter

Basic concepts

Java allows you to encapsulate multiple methods with the same name but different parameters in the same class into one method

Basic grammar

Access modifier return type method name (data type... Parameter name){

}

Precautions and use details

1. The arguments of variable parameters can be 0 or any number.

2. The arguments of variable parameters can be arrays.

3. The essence of variable parameters is array.

4. Variable parameters can be placed in the formal 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 formal parameter list

public class zaiOne {
    public static void main(String[] args) {
        Methods rn = new Methods();
        System.out.println(rn.sum(56,25,45,48));
    }
}
class Methods{
	public int sum(int...nums){
        int res = 0;
        for (int i= 0;i< nums.length;i++){
            res+=nums[i];
        }
        return res;
    }
}

Scope

1. In Java programming, the main variables are attributes (member variables) and local variables.

In the general definition of variables, we mean local variables.

3. Scope classification in Java

**Global variable: * * that is, attribute. The scope is the whole class body. Cat class: cry eat and other methods use attributes

**Local variables: * * that is, variables other than attributes. The scope is in the code block that defines it!

4. Global variables can be used directly without assignment, because there is a default value, and local variables can only be used after assignment, because there is no default value.

Pay attention to usage and details

1. Attributes and local variables can have the same name and follow the principle of proximity when accessing.

2. In the same scope, such as the same member method, two local variables cannot have the same name.

3. The attribute has a long life cycle. It is created with the creation of the object and dies with the death of the object. A local variable, with a short declaration cycle, is created with the execution of its code block and dies with the end of the code block. During a method call.

4. Different scopes

Global variable: it can be used by this class or other classes (called through objects)

Local variable: can only be used in the corresponding method in this class

5. Different modifiers

Global variables / attributes can be modified

Local variables cannot be decorated

Construction method and constructor

Basic introduction

Constructor, also known as constructor, is a special method of class. Its main function is to complete the initialization of new objects

1. Method name and class name must be the same

2. No return value

3. When creating an object, the system will automatically call the constructor of this class to initialize the object.

**Note: * * the modifier of constructor can be default, public, protected and private

Parameter lists have the same rules as member methods.

Basic grammar
Modifier method name (formal parameter list){

​	Method body;

}
Precautions and details

1. A class can define multiple different constructors, that is, constructor overloading

2. Constructor name and class name should be the same

3. The constructor has no return value

4. The constructor is to complete the initialization of the object, not to create the object

5. When creating an object, the system automatically calls the construction method of this class

6. If the programmer does not define a construction method, the system will automatically generate a default parameterless construction method for the class

(also called default construction method),

7. Once you define your own constructor, the default constructor is overwritten, and you can no longer use the default parameterless constructor,

Unless it's clearly defined

public class zaiThree {
    public static void main(String[] args) {
        Person p1 = new Person();
        System.out.println(p1.name+"  "+p1.age);
        Person p2 = new Person("Liu Zhicheng",26);
        System.out.println(p2.name+" "+p2.age);

    }
}
/**
 * Add two constructors to the previously defined Person class
 * The first nonparametric constructor uses the constructor to set everyone's age attribute with an initial value of 18
 * The second constructor with pname and page parameters
 * This enables the initialization of the age attribute and name attribute of the person object every time the person object is created
 * Use different constructors to create objects*/
class Person{
    String name;
    int age;
    public Person(){
        age = 18;
    }
    public Person(String pname ,int page){
        age = page;
        name = pname;
    }
}

Use of this

introduce

The Java virtual opportunity assigns this to each object to represent the current object.

Which object is called, this represents which object

Memory allocation for this

Precautions and instructions for this

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

2.this is used to distinguish the attributes and local variables of the current class

3. Syntax of accessing member method: this Method name (parameter list);

4. Access constructor syntax: this (parameter list) Note: it can only be used in the constructor (another constructor can only be accessed in the constructor);

Must be placed in the first statement

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

public class zaiThree {
    public static void main(String[] args) {
        Person p1 = new Person("marry",20);
        Person p2 = new Person("marry",30);
        //Output the comparison results of p1 and p2
        System.out.println(p1.compareTo(p2));

    }
}

class Person{
    String name;
    int age;
    public Person(String name ,int age){
        //This accesses the properties of this class
        this.name = name;
        this.age = age;
    }
    public boolean compareTo(Person p){
        //If the current attribute name is compared with the local attribute name and the current age = = local attribute age
        if (this.name.equals(p.name) && this.age == p.age){
            return true;
        }else {
            return false;
        }
    }
}