Don't understand classes and objects yet? It's better to take a few minutes to take a look at this simple class and object tutorial!!!

preface

Three directions of learning object-oriented

1, Classes and objects

Structure: attribute, method, constructor (must understand)

Code block, inner class (know how to use)

2, Three characteristics of object oriented

Encapsulation, inheritance, polymorphism

3, Use of other keywords

this, super, static, final, abstract, etc

Classes and objects

introduce

Process oriented: it emphasizes the functional behavior, taking the function as the minimum unit and considering how to do it

Example: people put elephants in the refrigerator

① open the refrigerator door

② put the elephant in

③ close the refrigerator door

Each behavior step is process oriented

Object oriented: emphasize the objects with functions, take the class / object as the minimum unit, and consider who will do it

Example: people put elephants in the refrigerator

① person{

Refrigerator Open ();

Elephants Enter ();

Refrigerator Close ();

​ }

② refrigerator{

Open ();

Close ();

​ }

③ elephant{

Enter ();

​ }

Subdivide each step into who will do it, what to do, how to do it, etc

Basic elements of the Java language: classes and objects (everything is an object)

1. Class is the description of a class of things, which is an abstract and conceptual definition

2. An object is each individual of such things that actually exist, so it is also called an instance.

Object oriented programming focuses on class design

A design class is a member of a design class

Simple description: a class is an abstraction of an object, and an object is an instance of a class

1, A design class is actually a member of a design class

Attribute = member variable = field = field / field (called in other languages)

Method = member method = method = function (called in other languages)

1. Attribute: the member variable in the corresponding class

2. Behavior: member methods in corresponding classes

2, Use of classes and objects (implementation of object-oriented ideas)

1. Create a class and design the members of the class

2. Create an instance of a class

3. Call the structure of an object through object. Property or object. Method

3, If multiple objects of a class are created, each object has a set of class properties independently (non static (i.e. without static keyword))

This means that if we modify attribute A of one object, it will not affect attribute A of another object

example:

public class Test_02 {
    public static void main(String[] args) {
        User user = new User();
        user.name = "Zhang San";
        // Return to Zhang San
        System.out.println(user.name);
        
        User user1 = new User();
        // Returns null because this is the data in a new object
       System.out.println(user1.name);
    }
}

class User {
    String name;
    int age;
}

4, Memory parsing of object

If the attribute in the object is not assigned a value, the default initial value of the corresponding type is obtained, such as 0, 0.0, null, etc

Use of properties in class

Attributes (member variables) and local variables

Similarities:

1. The format of defined variables is consistent: data type, variable name = variable value

2. Declaration before use

3. Variables have corresponding scopes

difference:

1. The positions declared in the class are different

Attribute: directly defined in {} (braces) of the class

Local variables: variables declared within methods, method parameters, code blocks, constructor parameters, and constructors

2. Different permission modifiers

Attribute: when declaring a variable (attribute), you can specify its permission and use the permission modifier

Local variables: permission modifiers are not allowed

Common permission modifiers: public, private, protected, default (default modifier)

3. Different default initial values

Attribute: there is a default initial value according to the corresponding type

Integer (short, byte, int, long): 0

Floating point (double, float): 0.0

​ char: '0'

​ boolean: false

Reference data type (class, array, interface): null

Local variable: no default initial value

Note: when calling a method, we can dynamically assign values to formal parameters, but variables defined inside the method cannot be assigned

4. The location loaded in memory is different

Properties: load into heap space (static variables in method area)

Local variables: loading into stack space

The attribute here is the member variable

Declaration and use of methods in classes

Method: describe the function that the class should have

For example: Math class (random number, etc.), Scanner class (console input), Arrays class (sorting, searching, etc.)

Method (void means that there is no return value. If it is a type, it needs to return a value of the corresponding type)

grammar

Access modifier return type method name () {method body}

Access modifier return type method name (formal parameter list) {method body}

Use of methods

1. Method, you can call the properties and methods in the current class

Method can be called, and you can call yourself;

For example, calling the A method in the A method is called recursive call. However, this operation cannot be used at will, and the wrong call may cause stack memory overflow!

2. Method can call other methods, but cannot define other methods!

Use of the return keyword

1. Scope of use: used in the method body

2. Function:

  1. End a method
  2. For methods with return values, use the "return data" method to return the required data

Note: no other execution statements can be written under return!

explain

1. Permission modifiers: public, protected, default (default modifier), private

2. Return value Description: there is a return value and there is no return value

  1. If a method has a return value, the type of the return value must be specified when the method is declared; At the same time, the return keyword needs to be used in the method to return the value of the specified type

  2. If the method has no return value, it needs to be identified with void (return is not required when there is no return value. If it needs to be used, you can write return directly without adding the corresponding return value)

  3. Should there be a return value when defining a method?

    Write according to the corresponding requirements! For example, if all elements in the array are queried and displayed to the user for viewing, the return value needs to be used at this time

3. Method name: it belongs to the identifier and follows the rules and specifications of the identifier. The name needs to "see the name and know the meaning"

4. Formal parameters: 0, 1 or more parameters can be declared

  1. Format: data type 1, parameter 1, data type 2, parameter 2, data type N, parameter n... (separated by commas)

  2. Do you want formal parameters when defining methods?

    Write according to the corresponding requirements!

5. Method body: the embodiment of method function

Method overload

concept

  1. More than one method with the same name is allowed in the same class, as long as their parameter number or parameter type are different.
  2. Two are the same and different: the same class; The same method name; Number and type of different parameters
  3. The number and type of parameter lists are different
  4. Simply put, it is different parameters with the same name

characteristic

  1. It has nothing to do with the permission modifier, return value type, parameter variable name and method body of the method. It only depends on the parameter list, and the parameter list must be different (number of parameters or parameter types);
  2. When calling, it can be distinguished according to different method parameter lists!

case

/**
 * How to determine a specified method when calling a method through an object:
 * Method name - > parameter list
 */
public class Test_09 {
    public static void main(String[] args) {
        Test_09 test = new Test_09();
        test.getSum(1, 2);
        test.getSum(18, "Xiao Ming");
    }

    // The following three methods constitute overloading
    public void getSum(int i, int j) {
        System.out.println(i + j);
    }

    public void getSum(int age, String name) {
        System.out.println("My name is:" + name + ";this year" + age + "Years old");
    }

    public int getSum(char i, boolean j) {
        return 0;
    }

    // Error reconstruction
//    public void getSum(int i,int j){}
//    public int getSum(int q,int w){return 0;}
//    private void getSum(int r,int p){}
}

Varargs(variable number of arguments) mechanism

understand

Before JDK 5.0: array parameters are used to define methods, and multiple variables of the same type are passed in

public static void test(int a ,String[] books);

JDK 5.0: variable number formal parameters are used to define methods, and multiple variables of the same type are passed in

public static void test(int a ,String... books);

Specific use

  1. Format of variable number parameter: data type... Variable name
  2. When calling a method with variable number of formal parameters, the number of parameters passed in can be: 0, 1, 2, etc
  3. Variable number of formal parameter methods have the same name as the methods in this class, and methods with different formal parameters constitute overloads
  4. Arrays with variable number of formal parameter methods and the same method name and parameter type in this class do not constitute overloads (the two cannot coexist)
  5. The variable number parameter can only be declared at the end of the method parameter (because once declared at the front, the compiler will not know whether the parameter you pass in is for the first parameter or the second parameter)
  6. A variable number parameter can only be declared at most in a method parameter
public class Test_11 {
    public static void main(String[] args) {
        Test_11 test = new Test_11();
        test.show("Hello");
        test.show("J", "D", "K");

        test.show(new int[]{1, 2, 4, 5});
    }

    public void show(String i) {
        System.out.println("show(String i)");
    }

    public void show(int[] j) {
        System.out.println("show(int[] j)");
    }

    /*
        be careful:
        String... str And String[] str can only exist during refactoring
        For example, public void show(String... str) has been defined here
        Then public void show(String[] str) cannot be defined
     */
    public void show(String... str) {
        System.out.println("show(String... str)");

    }
}

Value Passing Mechanism of method parameters

Assignment of variables

  1. If it is a basic data type, the assigned value is the data value saved by the variable
  2. If it is a reference data type, the assigned value is the address value of the data saved by the variable

Basic data type cases

public class Test_12 {
    public static void main(String[] args) {
        int i = 10;
        int j = i;
        System.out.println(i + "---" + j);      // Return 10 --- 10

        j = 12;
        System.out.println(i + "---" + j);      // Return 10 --- 12

        Test test = new Test();
        test.name = "Xiao Ming";
        Test test1 = test;
        System.out.println(test.name + "---" + test1.name);     // Return to Xiaoming --- Xiaoming

        test1.name = "Xiaobai";
        System.out.println(test.name + "---" + test1.name);     // Return to Xiaobai --- Xiaobai
    }
}

class Test {
    String name;
    int age;
}

Reference data type case

public class Test_14 {
    public static void main(String[] args) {
        Data data = new Data();
        data.m = 10;
        data.n = 20;
        System.out.println(data.m + "---" + data.n);    // Return 10 --- 20
        
        Test_14 test = new Test_14();
        test.swap(data);
        /*
          Return 20 --- 10
          Because the reference data type specifies the data in the corresponding address value, and the object address here points to the same one, the exchange can be successful
        */
        System.out.println(data.m + "---" + data.n);    
    }

    /**
     * Exchange the values of m and n
     */
    public void swap(Data data){
        int temp = data.m;
        data.m = data.n;
        data.n = temp;
    }
}

class Data{
    int m;
    int n;
}

Method parameter passing mechanism

Formal parameters: parameters in parentheses declared when a method is defined

Argument: the data actually passed to the formal parameter when the method is called

Value Passing Mechanism:

  • If the parameter is a basic data type, the actual parameter is assigned to the data source where the formal parameter is actually stored
  • If the parameter is a reference data type, the address value of the stored data of the parameter is assigned to the formal parameter
import java.util.Arrays;

public class Test_13 {
    public static void main(String[] args) {
        int i = 10;
        int j = 20;
        System.out.println(i + "---" + j);

        // Swap two parameters
        Test_13 test = new Test_13();
        test.exchange(i, j);
        /*
            Return 10 --- 20
            Because i and j printed at this time are still the values in the mian method, not the data exchanged in the exchange method
         */
        System.out.println(i + "---" + j);


        int[] arr = new int[]{2, 4, 6, 3, 1, 9};
        test.bubbleSort(arr);
    }

    // Swap two parameters
    public void exchange(int i, int j) {
        int temp = i;
        i = j;
        j = temp;
        // Print 20-10, because i and j have completed the exchange at this time, and print the values that have been exchanged in the exchange method
        //System.out.println(i + "---" + j);
    }

    public void exchange2(int[] arr, int i, int j) {
        int temp = arr[i];
        arr[i] = arr[j];
        arr[j] = temp;
    }

    //Bubble sorting
    public void bubbleSort(int[] arr) {
        for (int i = 0; i < arr.length - 1; i++) {
            for (int j = 0; j < arr.length - 1 - i; j++) {
                if (arr[j] > arr[j + 1]) {
                    //int temp = arr[j];
                    //arr[j] = arr[j + 1];
                    //arr[j + 1] = temp;

                    /*
                        Error presentation:
                        You can replace the modified method with the correct result
                        Because each call is an argument in the exchange method, not a parameter of the current method, the final result will not be affected
                     */
                    //exchange(arr[j], arr[j + 1]);

                    /*
                        Correct presentation:
                        Pass the array to be sorted into the corresponding replacement method for replacement. At this time, the specified data is the data in the same address value
                     */
                    exchange2(arr, j, j + 1);
                }
            }
        }
        System.out.println(Arrays.toString(arr));
    }
}

Use of constructors (construction methods)

effect

  1. create object

  2. Initialize the properties of the object

explain

  1. If the class constructor is not explicitly defined, the system will provide an empty parameter constructor by default

  2. Defines the format of the constructor: permission modifier class name (formal parameter list) {}

  3. Multiple constructors can be defined in a class to form overloads with each other

  4. Once we manually define the constructor in the class (with or without parameters), the system will not provide the default null parameter constructor

  5. There will be at least one constructor in a class

  6. The default permissions (modifiers) of the constructor are consistent with those of the class

Note: construction method and method are not the same concept. Construction method is an independent structure!

public class Test_21 {
    public static void main(String[] args) {
        // Create an object of class
        Persons persons = new Persons();
        persons.eat();
    }
}

class Persons {
    // attribute
    String name;
    String age;

    // constructor 
    public Persons() {
        System.out.println("Persons()...");
    }

    public Persons(String name) {
        this.name = name;
    }

    public Persons(String name, String age) {
        this.name = name;
        this.age = age;
    }

    // method
    public void eat() {
        System.out.println("having dinner");
    }

    public void study() {
        System.out.println("study");
    }
}

practice

Simple exercise

  1. Write a program, declare a method method, print a 10*8 type rectangle in the method, call this method in main method.

  2. Modify the previous program. In the method method method, in addition to printing a 10 * 8 * type rectangle, calculate the area of the rectangle and take it as the return value of the method. Invoke the method in the main method, receive the returned area value and print it.

  3. Modify the previous program, provide m and n parameters in the method method method, print an m*n * type rectangle in the method, calculate the area of the rectangle, and take it as the return value of the method. Invoke the method in the main method, receive the returned area value and print it.

public class Test_06 {
    public static void main(String[] args) {
        ThreeExercises threeExercises = new ThreeExercises();
        // Print rectangle
        threeExercises.method();

        // Calculated area
        System.out.println("Area:" + threeExercises.rectangularArea());

        // Print a dynamic rectangle and calculate the area
        System.out.println("Area:" + threeExercises.calculateTheArea(3, 6));
    }
}

class ThreeExercises {
    /**
     * 1, Print 10 * 8 rectangle
     * If the function gives a specific effect, you can not add formal parameters
     */
    public void method() {
        // that 's ok
        for (int i = 0; i < 10; i++) {
            // column
            for (int j = 0; j < 8; j++) {
                System.out.print("*");
            }
            System.out.println();
        }
    }

    /**
     * 2, Calculate the area of the rectangle
     */
    public double rectangularArea() {
        method();
        return 10 * 8;
    }

    /**
     * 3, Print a dynamic rectangle and calculate the area
     */
    public double calculateTheArea(double m, double n) {
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                System.out.print("*");
            }
            System.out.println();
        }
        return m * n;
    }
}

Array object exercise

Define class Student, which contains three attributes: Student number(int), grade state(int), and score(int); Create 20 Student objects with Student numbers from 1 to 20. Grades and grades are determined by random numbers.

Question 1: print out the student information of grade 3 (state value is 3).

Question 2: use bubble sorting to sort students' grades and traverse all student information

Tips:

  1. Generate random number: math Random(), return value type double;

  2. Rounding: math Round (double D), return value type long.

public class Test_07 {
    public static void main(String[] args) {
        // Declare an array of objects to store student information
        Student[] student = new Student[20];

        Student user = new Student();
        user.createAStudent(student);

        /*
          1, Print third grade student information
         */
        Student stu = new Student();
        stu.findBasedOnGrade(student);

        /*
           2:  Use bubble sort to sort by student grade and traverse all student information
         */
        Student stus = new Student();
        stus.bubbleSort(student);
    }
}

class Student {
    /**
     * Student number
     * Grade state
     * score
     */
    int number;
    int state;
    int score;

    /**
     * Create students
     */
    public void createAStudent(Student[] student) {
        // Set user information according to requirements
        for (int i = 0; i < student.length; i++) {
            // An object can only store the information of one student, so we need to create multiple objects in the loop (otherwise null pointer exception will occur)
            student[i] = new Student();
            student[i].number = (i + 1);
            student[i].state = (int) (Math.random() * 3 + 1);
            student[i].score = (int) (Math.random() * 100 + 1);
        }
    }

    /**
     * 1, Print third grade student information
     */
    public void findBasedOnGrade(Student[] student) {
        for (Student s : student) {
            if (s.state == 3) {
                System.out.println("Student No.:" + s.number + ";Grade:" + s.state + ";Achievement:" + s.score);
            }
        }
    }

    /**
     * 2:  Use bubble sort to sort by student grade and traverse all student information
     */
    public void bubbleSort(Student[] student) {
        for (int i = 0; i < student.length - 1; i++) {
            for (int j = 0; j < student.length - 1 - i; j++) {
                if (student[j].score < student[j + 1].score) {
                    int temp = student[j].score;
                    student[j].score = student[j + 1].score;
                    student[j + 1].score = temp;
                }
            }
        }
        for (Student s : student) {
            System.out.println("Student No.:" + s.number + ";Grade:" + s.state + ";Achievement:" + s.score);
        }
    }
}

Method overload exercise

1, Write a program, define three overloaded methods and call. The method name is mOL.

  1. The three methods receive an int parameter, two int parameters and a string parameter respectively.
  2. Perform the square operation and output the result, multiply and output the result, and output the string information.
  3. In the main () method of the main class, call three methods with parameters respectively.

2, Define three overloaded methods (max)

  1. The first two methods of finding the maximum value of int;
  2. The second method is to find the maximum of the two double values;
  3. The third method is to find the maximum of the three double values;
  4. Call three methods respectively.
public class Test_10 {
    public static void main(String[] args) {
        Test_10 test = new Test_10();
        test.mOL(10);
        test.mOL(2, 4);
        test.mOL("little cat");

        System.out.println(test.max(24, 31));
        System.out.println(test.max(10.0, 7.0));
        System.out.println(test.max(12, 5, 6));
    }

    public void mOL(int sum) {
        System.out.println(sum * sum);
    }

    public void mOL(int i, int j) {
        System.out.println(i * j);
    }

    public void mOL(String val) {
        System.out.println(val);
    }

    public int max(int i, int j) {
        if (i < j) {
            return i;
        }
        return j;
    }

    public double max(double a, double b) {
        return a > b ? a : b;
    }

    public double max(double i, double j, double k) {
        double max = (i > j) ? i : j;
        return (max > k) ? max : k;
    }
}

Passing an object as a parameter to a method

  1. Define a Circle class, including a double radius attribute representing the radius of the Circle, and a findArea() method to return the area of the Circle.

  2. Define a class PassObject and a method printAreas() in the class. The method is defined as follows:

    public void printAreas(Circle c, int time)

    In the printAreas method, print out each integer radius value from 1 to time and the corresponding area.

    For example, if times is 5, the radius 1, 2, 3, 4, 5 and the corresponding circle area are output.

  3. The printAreas() method is invoked in the main method, and the current radius value is output after the call is completed.

    The program running results are shown in the figure:

public class Test_16 {
    public static void main(String[] args) {
        PassObject passObject = new PassObject();
        // When you use an object only once, you can write it as an anonymous object
        passObject.printAreas(new Circles(), 5);
    }
}

class Circles {
    double radius;

    public double findArea() {
        return Math.PI * radius * radius;
    }
}

class PassObject {
    public void printAreas(Circles c, int time) {
        for (int i = 0; i < time; i++) {
            c.radius = (i + 1);
            System.out.println((i + 1) + "\t" + c.findArea());
        }
        System.out.println("new radius is " + (time + 1));
    }
}

Recursive Method

explain

  1. A method body calls itself
  2. Method recursion contains an implicit loop that repeats a piece of code, but this repetition does not need loop control.
  3. Recursion must recurse in the known direction, otherwise this recursion will become infinite recursion, similar to an endless loop.
public class Test_17 {
    public static void main(String[] args) {
        Test_17 test = new Test_17();
        System.out.println("Case 1:" + test.getSum(100));

        System.out.println("Case 2:" + test.f(10));

        System.out.println("Case 3:" + test.Fibonacci(9));
    }

    /**
     * Case 1
     * Calculate the sum of all natural numbers between 1-100
     */
    public int getSum(int num) {
        if (num == 1) {
            return 1;
        } else {
            return num + getSum(num - 1);
        }
    }

    /**
     * Case 2
     * It is known that there is a sequence: f(0) = 1,f(1) = 4,f(n + 2) = 2 * f(n + 1) + f(n)
     * Where n is an integer greater than 0, find the value of f(10)
     */
    public int f(int n) {
        if (n == 0) {
            return 1;
        } else if (n == 1) {
            return 4;
        } else {
            // Error: exception in thread "main" Java Lang. stackoverflowerror (stack overflow)
            //return f(n + 2) - 2 * f(n + 1);

            return 2 * f(n - 1) + f(n - 2);
        }
    }

    /**
     * Case 3: Fibonacci sequence
     * Enter a data n and calculate the nth value of Fibonacci sequence
     * 1 1 2 3 5 8 13 21 34 55
     * Law: a number is equal to the sum of the first two numbers
     * Requirements: calculate the nth value of Fibonacci sequence and print out the whole sequence
     */
    public int Fibonacci(int n) {
        return n < 2 ? 1 : (Fibonacci(n - 1) + Fibonacci(n - 2));
    }

    /**
     * Case 4: Hanoi Tower problem
     * Case 5: quick sorting
     * Self Baidu
     */
}

Use the construction method to calculate the area of the triangle

Write two classes, TriAngle and TriAngleTest. The TriAngle class declares the private bottom long base and high H eight, and declares the public method to access the private variable.

In addition, provide the necessary constructors for the class. Another class uses these common methods to calculate the area of a triangle.

public class TriAngleTest {
    public static void main(String[] args) {
        TriAngle triAngle = new TriAngle(2, 4.3);
        System.out.println("The triangle area is:" + triAngle.getBase() * triAngle.getHeight());

    }
}

class TriAngle {
    /**
     * Bottom length: base
     * Height: height
     */
    private double base;
    private double height;

    public TriAngle() {
    }

    public TriAngle(double base, double height) {
        this.base = base;
        this.height = height;
    }

    public double getBase() {
        return base;
    }

    public void setBase(double base) {
        this.base = base;
    }

    public double getHeight() {
        return height;
    }

    public void setHeight(double height) {
        this.height = height;
    }
}

Constructor exercise

  1. Define the Student class, which has four properties:

    String name;
    int age;
    String school;
    String major;
    
  2. Define three constructors of Student class:

    The first constructor Student(String n, int a) sets the name and age attributes of the class;

    The second constructor Student(String n, int a, String s) sets the name, age and school properties of the class;

    The third constructor Student(String n, int a, String s, String m) sets the name, age, school and major properties of the class;

  3. Call the objects created by different constructors in the main method and output their attribute values.

public class Test_24 {
    public static void main(String[] args) {
        Student students1 = new Student("Xiao Ming", 18);
        System.out.println(students1.getName() + "---" + students1.getAge());

        Student students2 = new Student("Xiaomei", 12, "tsinghua");
        System.out.println(students2.getName() + "---" + students2.getAge() + "---" + students2.getSchool());

        Student students3 = new Student("Xiao Cang", 26, "Peking University", "heiheihei");
        System.out.println(students3.getName() + "---" + students3.getAge() + "---" + students3.getSchool() + "---" + students3.getMajor());
    }
}

class Student {
    private String name;
    private int age;
    private String school;
    private String major;

    public Students() {
    }

    public Students(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public Students(String name, int age, String school) {
        this.name = name;
        this.age = age;
        this.school = school;
    }

    public Students(String name, int age, String school, String major) {
        this.name = name;
        this.age = age;
        this.school = school;
        this.major = major;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public String getSchool() {
        return school;
    }

    public void setSchool(String school) {
        this.school = school;
    }

    public String getMajor() {
        return major;
    }

    public void setMajor(String major) {
        this.major = major;
    }
}

understand

1, Object oriented and process oriented (understanding)

Object oriented: it emphasizes the function behavior, and takes the function as the minimum unit to consider how to do it

Process oriented: emphasize the objects with functions, take the class / object as the minimum unit, and consider who will do it

2, The idea of completing a project (or function)

Ideas and steps of analyzing problems with object-oriented analysis method:

  1. According to the needs of the problem, select the real-world entity targeted by the problem.
  2. Find the attributes and functions related to solving problems from entities, and these attributes and functions form classes in the conceptual world.
  3. Abstract entities are described in computer language to form the definition of classes in the computer world. That is, with the help of a program language, the class is constructed into a data structure that can be recognized and processed by the computer.
  4. Instantiate a class into an object in the computer world. Object is the ultimate tool to solve problems in the computer world.

3, Two important concepts in object oriented

Classes and objects

Relationship: a class is an abstraction of an object, and an object is an instance of a class

4, Rules for implementation of object-oriented ideas

  1. Create a class and design the members of the class
  2. Create an object of class
  3. Call the structure of an object through object. Property or object. Method

5, Object creation and object memory parsing

Case code:

User user = new User();
User user2 = new User();
User user3 = user;
user3.age = 18;

explain

If you create multiple objects of a class, each object has a set of class properties independently (which means that if you modify property a of one object, it will not affect property a of another object)

Memory parsing

6, Understand "everything is connected to the object"

  1. In the java language, we encapsulate functions and structures into classes, and call specific function structures through class instantiation
  2. When it comes to the interaction between the java language and the front-end html and back-end databases, the front-end and back-end structures are embodied as classes and objects at the java level

7, Use of anonymous objects

Understanding: the object we created is not explicitly assigned a variable name, that is, it is an anonymous object
Feature: anonymous objects can only be called once

public class Test_08 {
    public static void main(String[] args) {
        Phone phone = new Phone();
        phone.sendEmail();
        phone.playGame();
        
        // Use of anonymous objects
        new Phone().sendEmail();
        new Phone().playGame();

        new Phone().price = 10;
        new Phone().showPrice();   // Returns 0.0 because each time a new object is created

        /*
            Anonymous objects are generally used in projects in the following cases
         */
        Phone phone1 = new Phone();
        phone1.show(phone);         // In the previous method, the specified object is passed in as a parameter
        phone1.show(new Phone());   // Using anonymous objects, create a new object as a parameter
    }
}

class Phone {
    /**
     * Price
     */
    double price;

    public void sendEmail() {
        System.out.println("Send mail");
    }

    public void playGame() {
        System.out.println("play a game");
    }

    public void showPrice() {
        System.out.println("The price is:" + price);
    }

    public void show(Phone phone){
        sendEmail();
        playGame();
        showPrice();
    }
}

8, Benefits of custom tool classes

  1. The code looks more concise
  2. Enhance code reusability (prevent code redundancy)

a minor question

1, What is method overloading?

"Two same and different": the same class and the same method name; The parameter list is different

How to call the determined method: method name - > parameter list

2, Explain the specific performance of the parameter passing mechanism in java methods

When the parameter is a basic data type, the value itself is passed;

When the parameter is a reference data type, the address value is passed;

3, What are the differences between member variables and local variables in declared locations, default values, permission modifiers, and memory allocation locations?

Declaration location: member variables are declared in the class and local variables are declared in the method

Default value: member variables have default values of corresponding types, while local variables have no default values

Permission modifier: member variables can be modified with permission modifiers, but local variables cannot

Memory allocation: member variables (new variables) are placed in the heap and local variables are placed in the stack

understand

1, The values of other types of data in the array will be printed, and the values of other types of data in the array will be returned directly

public class Test_15 {
    public static void main(String[] args) {
        int[] arr = new int[]{1, 2, 3};
        System.out.println(arr);    // Address value

        char[] arrs = new char[]{'a', 'b', 'c'};
        /*
           Return to abc
           Because java configures a separate API for the cahr array type
         */
        System.out.println(arrs);

        String[] str = new String[]{"aa", "bb", "cc"};
        System.out.println(str);  // Address value
    }
}

extend

Attribute assignment process

Location of assignment:

  1. Default initialization value

  2. Explicit initialization value (manual assignment)

  3. Initialization in constructor

  4. Assignment by "object. Property" or "object. Method"

Sequence of the above assignments: ① - ② - ③ - ④

JavaBean

JavaBean is a reusable component written in the Java language.

JavaBean s refer to Java classes that meet the following standards:

  1. Class is public

  2. There is a public constructor without parameters

  3. There are properties and corresponding get and set methods

Users can use JavaBeans to package functions, processing, values, database access and any other objects that can be created with Java code, and other developers can use these objects through internal JSP pages, servlets, other JavaBeans, applet programs or applications. Users can think that JavaBeans provide a function of copying and pasting anytime, anywhere without caring about any changes.

UML class diagram

  1. +Indicates public type, - indicates private type, # indicates protected type
  2. Method writing: method type (+, -); Method name (parameter name: parameter type): return value type

MVC design pattern

MVC is one of the common design patterns, which divides the whole program into three levels: view model layer, controller layer and data model layer. This design mode that separates program input and output, data processing and data display makes the program structure flexible and clear. At the same time, it also describes the communication mode between various objects of the program and reduces the coupling of the program.

Introduction to main packages in JDK (understand)

  1. java.lang ---- contains some core classes of Java language, such as String, Math, Integer, System and Thread, and provides common functions
  2. java.net ---- contains classes and interfaces that perform network related operations.
  3. java.io - contains classes that can provide multiple input / output functions.
  4. java.util - contains some utility classes, such as defining system features, collection framework classes of interfaces, and using functions related to date and calendar.
  5. java.text ---- contains some Java formatting related classes
  6. java.sql ---- contains Java classes / interfaces related to JDBC database programming
  7. java.awt --- contains several classes that make up the abstract window toolkits, which are used to build and manage the graphical user interface (GUI) of the application. B/S C/S

Keywords: Java OOP

Added by venkat20 on Mon, 03 Jan 2022 04:24:10 +0200