day07_ Introduction to object oriented (member variables, member methods) ②

Class properties (member methods)

Member variables are used to store the data information of objects, so how to represent the behavior and function of objects? It should be realized through methods

Concept of method

Method, also known as function, is the definition of an independent function and the most basic functional unit in a class. The purpose of encapsulating a function as a method is to realize code reuse and reduce the amount of code.

Principle of method

  • Must be declared before use. Classes, variables, methods, etc. should be declared before use
  • Do not call, do not execute, call and execute once.

Member methods fall into two categories

  • Instance method: a method without static modification must be called through an instance object.
package demo01;

//Declare a circle graphic class,
//For objects with different circles and different radius values, the area is also different, so area() here is non-static
public class Circle {
    //	Attributes (member variables): radius,
    double radius;

    //	Member method: the method of calculating area and returning circular object information
    double area() {
        return Math.PI * radius * radius;
    }
}
  • Static method: a method decorated with static, also known as class method, can be called by class name.
/*
CountTools It's just a tool class. The function of finding the maximum value of two integers has nothing to do with the CountTools object,
Therefore, it is better to declare the max method as static. Of course, it can also be declared as non static,
It's just that the CountTools object needs to be created when calling.
 */
class CountTools {//Declare a calculation tool class CountTools:
    //Find the maximum of two integers
    static int max(int a, int b) {
        return a > b ? a : b;
    }
}

How to declare methods

The position of method declaration must be outside the method in the class. Example of declaration position:

Syntax format

Format details:

  • Modifiers: modifiers are introduced one by one later. For example, public and static are modifiers
  • Return value type: the data type representing the result of the method operation. After the method is executed, the result is returned to the caller. The data types that can be written can be, basic data type and reference data type. If you do not need to return data to the caller, you can use void to decorate it.
  • Method name: give a name to the method. See the name to know the meaning, which can accurately represent the function of the method
  • Parameter list: data from other methods needs to be used inside the method, and the data needs to be transferred through parameter transfer. It can be basic data type, reference data type, or no parameters and nothing is written
  • Method body: specific function code
  • Return: ends the method and returns the result of the method. If the return value type is not void, there must be a return value in the method body; Statement, 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 the return value, or even there may be no return statement. No other code can be written after the return statement, otherwise an error will be reported: Unreachable code

When calling, if the method has a return value, it can accept or process the result of the return value. Of course, it can also not receive it. At this time, the return value is lost. If the return value type of the method is void, you do not need and cannot receive and process the return value result.

How to call methods in other classes

Example method

Code example

class Circle{
    double radius;
    public double area() {
        return Math.PI * radius * radius;
    }
}
public class TestCircle {
    public static void main(String[] args) {
        //create object
        Circle c1 = new Circle();
        //Assign values to member variables
        c1.radius = 1.2;
        System.out.println("c1 Area:" + c1.area());
        //Non static methods can only pass through 'object' Visit
        //	System. out. Println ("area of C1:" + Circle.area()); error

        Circle c2 = new Circle();
        c2.radius = 2.5;
        System.out.println("c2 Area:" + c2.area());
    }
}

Class method

Code example

class CountTools{
    static int max(int a, int b) {
        return a > b ? a : b;
    }
}
public class TestCount {
    public static void main(String[] args) {
        //Class name Class method ([argument list]) score call, recommended
        System.out.println(CountTools.max(4, 1));//4

        //Static methods can also be passed through "object." Access, not recommended
        CountTools c = new CountTools();
        System.out.println(c.max(2, 5));//5
    }
}

Access the member variables and member methods of this class in this class

Direct use, without adding "object name." and "class name.". The only exception: static methods cannot directly access non static member variables and member methods of this class

class Test{
		
	static void test(){
		System.out.println("");
	}
	void method(){
		 test();
	}
    
    public static void main(String[] args){
        method();//error
        test();//correct
    }
}

Requirements: design a method to obtain the larger value of two int numbers, and the data comes from the parameters

package demo01;

/*
1.Concept of method:
	Is to organize code blocks with independent functions into a whole and make them have code sets with special functions.
    Enclose a piece of code with special functions with curly braces {}, add necessary modifiers, and give a name for easy use

2.Format of method:
	Modifier return value type method name (data type 1, variable name 1, data type 2, variable name 2...) {
    	Function code;
        return Return value; / / if return is followed by specific result data, return cannot be omitted
    }
	be careful:
		(1)Method has no parameters, so you don't need to write the parameter list, but you must keep parentheses ()
        (2)No return value is returned to the caller inside the method. The return value type must be fixed and written as void

3.Format interpretation:
	(1)Modifier: public static is written in a fixed way. Remember first
    (2)Return value type: tell the caller of the method what type of data I will give you after the method ends
		The specific type of result data that needs to be returned to the caller of the method after the function code of the method is executed
        give an example:
			If the method returns the integer number 100 internally, the return value type is written as int
            If the method returns the decimal number 6.6 internally, the return value type is written as double
            If the method returns true/false internally, the return value type is written as boolean
    (3)Method name:
		Give the method a name (in accordance with the naming specification of identifiers and the principle of small hump (the first word is lowercase and the first letter of other words is uppercase)), which is convenient to use

    (4)Parameter list: what kind of data do you need to give me when you call my method
        When defining a method, one or more variables are defined in parentheses ()
		Example of defining method parameter list:
			(int a): When calling a method, you must pass an int type of data to the method
            (int a,int b): When you call a method, you must pass two int type data to the method
            (double a,double b): When calling a method, you must pass data of two double types to the method

    (5)Function code: one line / multiple lines of code to complete special functions
    (6)return Return value / result data;:
		a.End method
        b.Return the return value / result data after return to the method call


5.Three elements of defining methods
	(1)Method name:
	(2)Parameter list:
	(3)Return value type:

6.be careful:
	    After the method is defined, it will not be called or executed
        Method can be called any number of times
 */
public class Demo03Method {
    public static void main(String[] args) {

        System.out.println("main...start...");

        //Calling method: constant passed
        int result = getMax(100, 200);
        System.out.println("100 And 200 max: " + result);//Maximum of 100 and 200: 200

        //Calling methods: passing variables
        int a = 10, b = 20;
        int max = getMax(a, b);
        System.out.println(a + "and" + b + "Maximum value of: " + max);//Maximum of 10 and 20: 20

        System.out.println("main...end...");

    }

    //Design a method to obtain the larger value of two int numbers, and the data comes from the parameters
    /*
        When you call my method getMax, you must pass me two int type data,
        After the internal execution of the getMax method, I will return you an int type data
        You: the caller of the method
        Me: the method itself
        In (parameter) out (return value)
     */
    //int: tell the caller of the method that the specific type of data will be returned after the method function code is executed (what kind of data will be returned)
    public static int getMax(int a, int b) {

        int max = (a > b) ? a : b;

        return max;//End the method and return the data in max to the caller of the method
    }
}

Graphic analysis:

Difference between formal parameters and actual parameters

  • Formal parameters: when defining a method, the variables declared in parentheses after the method name are called formal parameters (formal parameters for short), that is, the formal parameters appear when the method is defined.
  • Argument: when calling a method, the value / variable / expression used in parentheses after the method name is called an actual parameter (argument for short), that is, the argument appears when the method is called.

When calling, you need to pass "arguments". The number, type and order of arguments should correspond to the formal parameter list one by one. If the method has no formal parameters, you don't need or can't pass arguments.

Code example

package demo01;

/*
    Difference between formal parameters and actual parameters
        1.Formal parameters:
            (1)Concept: the parameters (defined variables) defined in () when defining a method are called formal parameters
            (2)characteristic:
                a.When defining formal parameters, there are no values
                b.When the method is called, the formal parameter will have a value

        2.Actual parameters:
            (1)Concept: the parameters (constants / variables) given in () when calling a method are called actual parameters
            (2)characteristic:
                a.Data (constant / variable) written in () when method is called
                b.You must have a value
 */
public class ParamDiff {
    public static void main(String[] args) {
        System.out.println("main...start...");
        /*
            2.Actual parameters:
                (1)Concept: the parameters (constants / variables) given in () when calling a method are called actual parameters
                (2)characteristic:
                    a.Data (constant / variable) written in () when method is called
                    b.You must have a value
         */
        //Calling methods: passing constants
        printSum(10, 20);//10,20 are called actual parameters

        //Calling methods: passing variables
        int m = 100, n = 200;

        printSum(m, n);//m. N is called the actual parameter


        System.out.println("main...end...");
    }

    /*
        1.Formal parameters:
            (1)Concept: the parameters (defined variables) defined in () when defining a method are called formal parameters
            (2)characteristic:
                a.When defining formal parameters, there are no values
                b.When the method is called, the formal parameter will have a value
     */
    //Define a method to print the sum of two int numbers
    public static void printSum(int a, int b) {
        int sum = a + b;
        System.out.println("and: " + sum);
        return;//End the method and return to the calling place of the method. Note that no data is brought back
    }
}

Graphical formal parameters and arguments

Method call memory analysis

The method does not call or execute, and the call is executed once at a time. Each call will have a stack entry action in 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 is completed, the memory will be released, which is called out of the stack. If the method has a return value, the result will be returned to the calling function. If there is no return value, It ends directly, returns to the call and continues to execute the next instruction.

Parameter passing mechanism of method

Basic types are passed as method parameters

public class Test1 {
    /*
         Method parameters are passed as basic data types:

                The value passed into the method is a specific value
     */
    public static void main(String[] args) {
        int number = 100;
        System.out.println("call change Before method:" + number);
        change(number);
        System.out.println("call change After method:" + number);
    }

    public static void change(int number) {
        number = 200;
    }
}

Conclusion:

  • The change of basic data type parameters and formal parameters does not affect the actual parameters

Basis of conclusion:

  • Each method has an independent stack space in the stack memory. After the method runs, it will pop up and disappear

Method parameter passing reference type

public class Test2 {
    /*
         Method parameters are passed as reference data types:

                The passed in method is the memory address
     */
    public static void main(String[] args) {
        int[] arr = {10, 20, 30};
        System.out.println("call change Before method:" + arr[1]);
        change(arr);
        System.out.println("call change After method:" + arr[1]);
    }

    public static void change(int[] arr) {
        arr[1] = 200;
    }
}

Conclusion:

  • For parameters of reference type, the change of formal parameters will affect the value of actual parameters

Basis of conclusion:

  • Referring to the parameters of the data type, the address value is passed in. In memory, two references will point to the same memory. Therefore, even if the method bounces the stack, the data in the heap memory is the result of the change

Method overloading

Method overloading: more than one method with the same name is allowed in the same class, as long as their parameter lists are different, regardless of modifiers and return value types.

Different performance of parameter list:

  • The number of data types is different
  • Different data types
  • Data types are in different order

Overloaded method call: the JVM calls different methods through the parameter list of the method.

Code example

package demo01;

//Use the idea of method overloading to design a method to compare whether two data are equal, which is compatible with all integer types (byte,short,int,long)
public class Demo04 {
    public static void main(String[] args) {
        //5. Call the above four methods respectively
        System.out.println(compare(10, 20));
        System.out.println(compare((byte) 10, (byte) 20));
        System.out.println(compare((short) 10, (short) 20));
        System.out.println(compare(10L, 20L));
    }

    // Two byte type
    public static boolean compare(byte a, byte b) {
        System.out.println("byte");
        return a == b;
    }

    // Two types of short
    public static boolean compare(short a, short b) {
        System.out.println("short");
        return a == b;
    }

    // Two int s
    public static boolean compare(int a, int b) {
        System.out.println("int");
        return a == b;
    }

    // Two long type
    public static boolean compare(long a, long b) {
        System.out.println("long");
        return a == b;
    }
}

Keywords: Java

Added by Scottmandoo on Sat, 11 Dec 2021 05:56:01 +0200