day06_ Object oriented (member variables, methods)

Keywords: Java

Overview of object-oriented thinking

Java language is an object-oriented programming language, and object-oriented idea (OOP) is a programming idea. Under the guidance of object-oriented idea, we use java language to design and develop computer programs. The object here generally refers to all things in reality, and each thing has its own attributes and behavior. The object-oriented idea is the design idea of abstracting the attribute characteristics and behavior characteristics of things with reference to real things in the process of computer programming and describing them as computer events. It is different from the process oriented idea (POP), which emphasizes that the function is realized by calling the behavior of the object, rather than operating and realizing it step by step. Three characteristics of object-oriented: Encapsulation   (Encapsulation) inheritance   (Inheritance) polymorphism   (Polymorphism)

The difference between object oriented and process oriented

  • Process oriented: take the function (method) as the minimum unit, the data is independent of the function, focus on the process and steps, and consider how to do. Pay attention to the process. We must be clear about each step and realize it step by step
  • Object oriented: taking class / object as the minimum unit, class includes: data + method, focusing on the object (who), considering who will do it and who can do it. Focus on the object, do not need to know each step, just use the object call behavior to complete the requirements

Object oriented still includes process oriented, but the focus has changed and who will do it

Relationship between classes and objects

Overview of classes

Class is a general term used to describe a class of things with common attributes and behaviors. Therefore, in fact, classes do not exist in the objective world. They are abstract and are only used to describe data information.

Composition of classes

  • Class attribute: the state information of the object. For example: mobile phone attributes, brand, price
  • Class behavior: is what the thing can do. For example: mobile phone behavior, making phone calls, sending text messages

Overview of objects

An object is an instance of a class, which exists concretely, can be seen and touched, and has the properties and behavior of such things

  • Properties of an object: the properties of an object have specific values. For example, the attributes of mobile phone objects, such as brand Huawei and price 1999. The property of the object has a specific value, and the property in the class has no specific value
  • Object behavior: the behavior that an object can manipulate. For example: the behavior of mobile phone objects, using the call function, using the SMS function. Objects can use behavior

Relationship between classes and objects

  • Class is a general term for a class of things with common attributes and behaviors. It is abstract
  • An object is a concrete instance of a class of things. It is a tangible, tangible, real entity
  • A class is an abstraction of an object, and an object is an entity of a class
  • Objects are created according to classes. There are objects in a class. You can regard a class as the data type of an object

Class definition and object creation

A class of things in the real world:

  • Attribute: state information of things.
  • Behavior: what things can do.

The same is true for describing things with class in Java:

  • Member variable: the attribute of the corresponding thing
  • Member method: behavior of corresponding things

Define class: defines the members of a class, including member variables and member methods.

Class definition

 

Member variables: almost the same as previously defined variables. It's just that the location has changed. In a class, outside a method.

Member method: similar to the format of the main method written before. But the functions and forms are richer. In a class, outside a method.

The steps for Java custom classes are generally as follows:

  1. Define class (consider modifier and class name)
  2. Write the properties of the class (consider modifier, property type, property name, initialization value)
  3. Write the methods of the class (consider modifiers, return value types, method names, formal parameters, etc.)

Code example

public class Student {
    // Member variables: properties
    /**
     * full name
     */
    String name;
    /**
     * Age
     */
    int age;

    // Member methods: behavior
    /**
     * Learning function
     */
    public void study(){
        System.out.println("The students are studying Java...");
    }

    /**
     * Function of doing homework
     */
    public void doHomeWork(){
        System.out.println("The students are doing their homework and typing the code...");
    }
}

Object creation

Instantiation of a java class, that is, the object that creates the class. The format is as follows

        

  Now let's create the object of the Student class

public class Test {
    public static void main(String[] args) {
        // Requirements: first define a student class, and then define a student test class. In the student test class, the use of member variables and member methods is completed through objects
        // Create student object
        Student stu = new Student();

        // Accessing member variables
        stu.name = "Bingbing";
        stu.age = 18;
        System.out.println(stu.name + "," + stu.age);// Bingbing, 18

        // Access member method
        stu.study();
        stu.doHomeWork();

    }
}

Summary:

  • Create a new object using the new + constructor
  • Use "object name. Object member" to access object members (including properties and methods)
  • Methods in the same class can directly access member variables in the class. (special case: static method accesses non static, and compilation fails.)
  • In different classes: first create the object to access the class, and then use the object to access the members defined in the class.

One of the members of the class: member variables (properties)

Classification of member variables

  • Instance variable: it is also called object attribute without static modification. It belongs to an object and is used through the object
  • Class variable: it is decorated with static, also known as class variable. It belongs to the whole class, not an instance

Difference between member variable (attribute) and local variable  

Difference between member variable (attribute) and local variable   There are many, mainly the following points

  • Different positions in the class: member variable (outside the method in the class) local variable (inside the method or on the method declaration)
  • Different locations in memory: member variables (heap memory) local variables (stack memory)
  • Different life cycles: member variables (exist with the existence of the object and disappear with the disappearance of the object) local variables (exist with the call of the method and disappear with the completion of the call of the method)
  • Different initialization values: member variable (with default initialization value) local variable (without default initialization value, it must be defined before assignment)

How to declare member variables

For example: declare a Chinese class

class Chinese{
    static String country;
    String name;
    char gender = 'male';//Explicit assignment
}

How to access class variables outside a class

How to access instance variables outside a class

Code example

class Chinese{
    static String country;//Static variable, unassigned
    String name;//Class variable, unassigned
    char gender = 'male';//Class variable, display assignment
}
public class TestChinese {
    public static void main(String[] args) {
        //Class name. Static member variable
        System.out.println(Chinese.country);
        //	System.out.println(Chinese.name); Error, non static member variable must be accessed through object
        
        //create object
        Chinese c1 = new Chinese();
        
        //Object name. Non static member variable
        System.out.println(c1.name);
        
        //Static member variables can also be accessed through the object
        //Object name. Non static member variable
        System.out.println(c1.country);
        System.out.println(c1.gender);
    }
}

Member variables have default values

Code example

class Student {
    /**
     * full name
     */
    String name;
    /**
     * Age
     */
    int age;
    /**
     * fraction
     */
    double score;
    char c;
}

public class Test {
    public static void main(String[] args) {
        /*
            Default values for member variables:
                Integer type: the default value is 0
                Decimal type: the default value is 0.0
                Boolean type: the default value is false
                Character type: the default value is the invisible character '\ u0000'
                Reference type: the default value is null
         */
        // Create Student object
        Student stu = new Student();
        // Accessing member variables
        System.out.println(stu.name);// null
        System.out.println(stu.age);// 0
        System.out.println(stu.score);// 0.0
        System.out.println("="+stu.c+"=");
    }
}

The values of class variables are shared by all objects, while the values of instance variables are independent of each object

class Chinese {
    static String country;
    String name;
    char gender;
}
public class TestChinese {
    public static void main(String[] args) {
        //create object
        Chinese c1 = new Chinese();
        Chinese c2 = new Chinese();
        //The value of the instance variable is independent of each object
        c1.name = "Zhang San";
        c2.name = "Li Si";
        c1.gender='male';
        c2.gender = 'female';
        //Assign a value to a class variable, and all objects of the class are shared
        Chinese.country = "China";//recommend

        System.out.println(c1.country + "\t" + c1.name + "\t" + c1.gender);//China 	 Zhang San 	 male
        System.out.println(c2.country + "\t" + c2.name + "\t" + c2.gender);//China 	 Li Si 	 female
    }
}

Class member 2: Party   method

Method: organize the code blocks with independent functions into a whole and make them have a code set with special functions. Methods in Java cannot exist independently. All methods must be defined in classes.

Member methods fall into two categories:

  • Instance method: a method without static modification must be called through an instance object.
  • Static method: a method decorated with static, also known as class method, can be called by class name.

How to declare methods

The location of the method declaration must be outside the method in the class

Syntax format:

Format details:

  • Modifier:   Keywords that modify the access permission and status of methods, such as public static  
  • Return value type: the data type representing the result of method operation. It can be any data type. After the method is executed, the result is returned to the caller. For example, if the method returns the integer number 100 internally, the return value type is written as int. No return value is returned to the caller inside the method. The return value type must be fixed and written as void
  • 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)). See the name and meaning, which can accurately represent the function of the method
  • Parameter list: data in 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 has no parameters, so you don't need to write the parameter list, but you must keep parentheses ()
  • Function code: one line / multiple lines of code to complete special functions
  • return value: 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

Code example

public class Test {
    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);

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

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

    }

    //Design a method to obtain the larger value of two int numbers, and the data comes from the parameters
    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

How to call methods in other classes

Example method

Class method

 

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.

Summary:

  • When calling, you need to pass "arguments", and the number, type and order of arguments should correspond to the formal parameter list one by one. If a method has no formal parameters, it does not need and cannot pass arguments.
  • 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.

Code example

/*
    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 Demo {
    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
    }
}

Method considerations

  • Methods cannot be nested (other methods are defined inside the defined method), and other methods can be called
  • Methods can be called nested
  • The return value type must match the data type returned by the return statement, otherwise the compilation fails.
  • You cannot write code after return. Return means that the method ends. All subsequent code will never be executed. It is invalid code.
  • void indicates that there is no return value. You can omit return or write return separately without data
  • Classes, variables, methods, etc. should be declared before use.  
  • 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

Parameter passing: it is understandable that when we want to call a method, we will pass the specified value to the parameters in the method, so that the parameters in the method have the specified value and can use the value to operate in the method. This transfer method is called parameter transfer.

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

Reference types are passed as method parameters

public class Test {
    /*
         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.

What are the different parameter lists in method overloading

  • Different number of parameters
  • Different parameter types
  • Multiple types in different order

What factors are independent of method overloading

  • It is independent of the name of the parameter
  • Independent of return value type
  • Modifier independent

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

  • Find the corresponding method by name
  • Find the corresponding method according to the number of parameters
  • Determine the final method to be called according to the type of the parameter (first: do type exact matching, second: do automatic type promotion matching if the exact matching cannot be found)

Code example

// 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 Test {
    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));
    }

    //1. Using the idea of method overloading, define the method compare for comparing two byte data
    public static boolean compare(byte a, byte b) {
        System.out.println("...Two byte...");
        return a == b;
    }

    //2. Using the idea of method overloading, define the method compare to compare two short data
    public static boolean compare(short a, short b) {
        System.out.println("...Two short...");
        return a == b;
    }

    //3. Using the idea of method overloading, define the method compare for comparing two int data
    public static boolean compare(int a, int b) {
        System.out.println("...Two int...");
        return a == b;
    }

    //4. Using the idea of method overloading, define the method compare to compare two long data
    public static boolean compare(long a, long b) {
        System.out.println("...Two long...");
        return a == b;
    }
}

Object memory graph

Memory is one of the important components of a computer. It is a bridge to communicate with the CPU. Its function is to temporarily store the operation data in the CPU and the data exchanged with external memory such as hard disk. As long as the computer is running, the CPU will transfer the data to be calculated to the memory for operation. When the operation is completed, the CPU will transmit the results. The program we write It is stored in the hard disk. The program in the hard disk will not run. It must be put into the memory to run, and the memory will be emptied after running. In order to run the program, the Java virtual machine must allocate and manage the memory space, and each area has a specific data processing method and memory management method.

  Explain in detail

  View the following code

class Student {
    
    String name;
    int age;
    
    public void study(){
        System.out.println("The students are studying Java...");
    }
    
    public void doHomeWork(){
        System.out.println("The students are doing their homework and typing the code...");
    }
}

public class Test {
    public static void main(String[] args) {
        // Create Student object
        Student stu = new Student();
        System.out.println(stu);// Hexadecimal address value

        // Accessing member variables
        stu.name = "Bingbing";
        stu.age = 18;
        System.out.println(stu.name+","+stu.age);

        // Access member method
        stu.study();
        stu.doHomeWork();
    }
}

Memory analysis: as shown in the following figure

  Conclusion:

  • As long as an object is created, a space will be opened up in the heap area (any new will open up a new space in the heap area). The relationship between objects and objects is independent of each other
  • As long as the method is called, a space will be opened in the stack area to execute the method
  • Multiple objects have different memory partitions in heap memory. Member variables are stored in the memory area of their respective objects, and member methods are shared by multiple objects
  • When the references of multiple objects point to the same memory space (the address values recorded by the variables are the same), as long as any object modifies the data in memory, then, no matter which object is used for data acquisition, it is the modified data.

Posted by scoobydoo9749 on Mon, 22 Nov 2021 14:01:24 -0800