Self study JAVA classes and objects, object memory diagram, member variables and local variables, encapsulation and manufacturing methods

1. Classes and objects

Comparison of object-oriented and process oriented ideas:

Process oriented: it is a process centered programming idea. Each step of realizing the function is realized by itself.

Object oriented: it is an object-centered programming idea, which realizes specific functions by commanding objects.

1.1 relationship between class and object

Everything that exists objectively is an object, so we often say that everything is an object.

Class understanding:

  • It is a kind of common behavior in real life;
  • A class is the data type of an object. A class is a collection of objects with the same attributes and behaviors;
  • Simple understanding: class is a description of real things.

Class composition:

  • Attribute: refers to the characteristics of things, such as mobile phone things (brand, price, size);
  • Behavior: refers to the operation that things can perform, such as mobile phone things (making phone calls and sending text messages).

Relationship between class and object:

  • Class: class is the abstraction of a class of things with common attributes and behaviors in real life;
  • Object: a real entity that can be seen and touched;
  • Simple understanding: class is a description of things, and the object is a concrete thing.

1.2 definition of class

Class consists of two parts: attribute and behavior:

Attribute: reflected in the class through member variables (variables outside the methods in the class);

Behavior: reflected in the class through member methods (compared with the previous methods, just remove the static keyword).

Class definition steps:

① definition class

② write the member variables of the class

③ write the member method of the class

public class Student {
    // Attribute: name, age
    // Member variable: the format of the variable is the same as that defined before, but the position has changed, outside the method in the class
    String name;
    int age;

    // Behavior: Learning
    // Member method: the format of the method is the same as that defined before, except that the static keyword is removed
    public void study(){
        System.out.println("study");
    }
}

1.3 creation and use of objects

Format for creating objects:

  • Class name object name = new class name ();

Format of calling member:

  • Object name Member variables;

  • Object name Member method ();

Example code:

public class TestStudent {
    /*
        Format for creating objects:
                Class name object name = new class name ();
        Format of calling member variable:
                Object name Variable name
        Format of calling member method:
                Object name Method name ();
     */
    public static void main(String[] args) {
        // Class name object name = new class name ();
        Student stu = new Student();
        // Object name Variable name
        // Default initialization value
        System.out.println(stu.name);  // null
        System.out.println(stu.age);   // 0

        stu.name = "Zhang San";
        stu.age = 23;

        System.out.println(stu.name);  // Zhang San
        System.out.println(stu.age);   // 23

        // Object name Method name ();
        stu.study();
        // com.itheima.object1.Student@b4c966a
        // Full class name (package name + class name)
        System.out.println(stu);
    }
}

1.4 case - creation and use of mobile phones

Requirements: first define a mobile phone class, and then define a mobile phone test class. In the mobile phone test class, the use of member variables and member methods is completed through objects.

analysis:

  • Member variables: brand, price

  • Member method: call and send text messages

  • Example code:

public class Phone {
    // Brand, price
    String brand;
    int price;

    // Call, text
    public void call(String name){
        System.out.println("to"+name+"phone");
    }

    public void sendMessage(){
        System.out.println("Mass texting");
    }
}
public class TestPhone {
    public static void main(String[] args) {
        // 1. Create object
        Phone p = new Phone();
        // 2. Assign values to member variables
        p.brand = "rice";
        p.price = 2999;
        // 3. Print the assigned member variables
        System.out.println(p.brand + "..." + p.price);
        // 4. Call member method
        p.call("A Qiang");
        p.sendMessage();
    }
}

2. Object memory diagram

2.1 single object memory diagram

2.2 multiple object memory diagram

Summary:

Multiple objects have different memory partitions in heap memory. Member variables are stored in their respective memory areas, and member methods are shared by multiple objects.

2.3 multiple objects point to the same memory map

Summary:

When the references of multiple objects point to the same memory space (the address value recorded by the variable is 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.

3. Member variables and local variables

3.1 differences between member variables and local variables

Different positions in the class: member variables (outside the method in the class) local variables (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 after the call of the method);
Different initialization values: member variable (with default initialization value) and local variable (without default initialization value, it must be defined before assignment).

4. Packaging

4.1 private keyword

Overview: private is a modifier that can be used to modify members (member variables, member methods);

Features: members modified by private can only be accessed in this class. If private modified member variables need to be used by other classes, corresponding operations are provided:

  • Provide a "get variable name ()" method to obtain the value of member variables. The method is decorated with public;

  • The "set variable name (parameter)" method is provided to set the value of member variables. The method is decorated with public.

Example code:

/*
    Student class
 */
class Student {
    //Member variable
    String name;
    private int age;

    //Provide get/set methods
    public void setAge(int a) {
        if(a<0 || a>120) {
            System.out.println("You gave the wrong age");
        } else {
            age = a;
        }
    }

    public int getAge() {
        return age;
    }

    //Member method
    public void show() {
        System.out.println(name + "," + age);
    }
}
/*
    Student testing
 */
public class StudentDemo {
    public static void main(String[] args) {
        //create object
        Student s = new Student();
        //Assign values to member variables
        s.name = "Lin Qingxia";
        s.setAge(30);
        //Call the show method
        s.show();
    }
}

4.2 use of private keyword

Requirements:

  • Define standard student classes and require name and age to be decorated with private
  • It also provides set and get methods and show methods that are convenient for displaying data
  • Create an object in the test class and use it. The final console output is Lin Qingxia, 30

Example code:

/*
    Student class
 */
class Student {
    //Member variable
    private String name;
    private int age;

    //get/set method
    public void setName(String n) {
        name = n;
    }

    public String getName() {
        return name;
    }

    public void setAge(int a) {
        age = a;
    }

    public int getAge() {
        return age;
    }

    public void show() {
        System.out.println(name + "," + age);
    }
}
/*
    Student testing
 */
public class StudentDemo {
    public static void main(String[] args) {
        //create object
        Student s = new Student();

        //Assign values to member variables using the set method
        s.setName("Lin Qingxia");
        s.setAge(30);

        s.show();

        //Use the get method to get the value of the member variable
        System.out.println(s.getName() + "---" + s.getAge());
        System.out.println(s.getName() + "," + s.getAge());

    }
}

4.3 this keyword

Overview: this modified variable is used to refer to member variables. Its main function is to (distinguish the problem of duplicate names of local variables and member variables).

  • If the formal parameter of the method has the same name as the member variable, the variable without this modifier refers to the formal parameter, not the member variable;
  • The formal parameter of the method does not have the same name as the member variable. The variable without this modifier refers to the member variable.

Code implementation:

public class Student {
    private String name;
    private int age;

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

    public String getName() {
        return name;
    }

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

    public int getAge() {
        return age;
    }

    public void show() {
        System.out.println(name + "," + age);
    }
}

4.4 this memory principle

Note: This represents the reference of the current calling method, the method of which object is invoked, and which object this represents.

Illustration:


4.5 packaging ideas

Package overview:

  • It is one of the three characteristics of object-oriented (encapsulation, inheritance and polymorphism);
  • It is the simulation of the objective world by object-oriented programming language. In the objective world, the member variables are hidden inside the object, and the outside world can not be operated directly.

Packaging principle:

  • Some information of the class is hidden inside the class, which is not allowed to be directly accessed by external programs, but the operation and access of hidden information are realized through the methods provided by the class;
  • The member variable private provides the corresponding getXxx()/setXxx() methods.

Packaging benefits:

  • The method is used to control the operation of member variables, which improves the security of the code;
  • The code is encapsulated by method, which improves the reusability of the code.

5. Construction method

5.1 format and execution timing of construction method

Format Note:

  • The method name is the same as the class name, and the case should be consistent
  • There is no return value type, not even void
  • No specific result can be brought back by run

Execution time:

  • Called when creating an object. Each time an object is created, the construction method will be executed
  • Constructor cannot be called manually

Example code:

class Student {
    private String name;
    private int age;

    //Construction method
    public Student() {
        System.out.println("Nonparametric construction method");
    }

    public void show() {
        System.out.println(name + "," + age);
    }
}
/*
    Test class
 */
public class StudentDemo {
    public static void main(String[] args) {
        //create object
        Student s = new Student();
        s.show();
    }
}

5.2 function of construction method

Used to initialize the data (properties) of the object

public class Student {
    /*
        Format:

               1. The method name should be the same as the class name, and the case should be the same
               2. There is no return value type, not even void
               3. There is no specific return value (return cannot bring back specific results)
     */

    private String name;
    private int age;

    // 1. If no constructor is written in a class, the system will provide a default parameterless constructor
    public Student(){}

    // 2. If the construction method is written manually, the system will no longer provide the default parameterless construction method
    public Student(String name, int age){
        this.name = name;
        this.age = age;
        System.out.println("I am Student Construction method of class");
    }

    public void show(){
        System.out.println(name + "..." + age);
    }
}
public class TestStudent {
    public static void main(String[] args) {
        Student stu1 = new Student("Zhang San",23);
        stu1.show();

        Student stu2 = new Student();
    }
}

5.3 precautions for construction method

Creation of construction method:

If no construction method is defined, the system will give a default parameterless construction method;

If the construction method is defined, the system will no longer provide the default construction method.

Recommended usage:

Whether it is used or not, manually write the nonparametric construction method and the parametric construction method

5.4 coding and use of standard classes

code:

/*
    JavaBean Class: encapsulating data
 */
public class Student {
    private String name;
    private int age;

    public Student() {
    }

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

    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 void show(){
        System.out.println(name + "..." + age);
    }
}

public class TestStudent {
    public static void main(String[] args) {
        // 1. Create an object with the nonparametric construction method and assign a value to the member variable through the setXxx method
        Student stu1 = new Student();
        stu1.setName("Zhang San");
        stu1.setAge(23);
        stu1.show();

        // 2. Directly assign values to attributes through the construction method with parameters
        Student stu2 = new Student("Li Si",24);
        stu2.show();
    }
}

Keywords: Java

Added by icon4tech on Thu, 17 Feb 2022 15:05:47 +0200