day07 [Class and Object-Object Memory Map-Encapsulation-Construction Method]

Posted by malam on Wed, 08 Dec 2021 18:40:39 +0100

1. Classes and Objects

A comparison of object-oriented and process-oriented ideas:

Process Oriented: A process-centric programming idea in which each step of functionality is achieved by itself

Object-oriented: An object-centric programming idea that implements specific functions by directing objects

1.1 Relationship between Classes and Objects

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

  • class
    • Understanding of classes
      • Class is the abstraction of a class of things with common attributes and behaviors in real life
      • A class is the data type of an object, and a class is a collection of objects with the same properties and behaviors
      • Simple understanding: class is a description of real things
    • Composition of classes
      • Attributes: refers to the characteristics of things, such as: mobile phone things (brand, price, size)
      • Behavior: refers to the actions that things can perform, such as: mobile phone things (phone calls, text messages)
  • Relationship between Classes and Objects
    • Class: Class is the abstraction of a class of things in real life that have common attributes and behaviors
    • Object: Is an entity that can see the real existence of the touch
    • Simple understanding: class is a description of things, object is a concrete thing

Definition of Class 1.2 [Application]

A class consists of attributes and behaviors

  • Attribute: In a class, represented by member variables (variables outside of methods in a class)
  • Behavior: Represent in the class by member method (remove the static keyword compared to the previous method)

Steps to define a class:

(1) Defining classes

(2) Writing member variables of classes

(3) Writing member methods of classes

public class Student {
    // Attributes: Name, Age
    // Member variables: just like the format of the previously defined variables, except the location has changed, outside of the methods in the class
    String name;
    int age;

    // Behavior: Learning
    // Membership method: Just like the format of the method defined earlier, the static keyword has been removed.
    public void study(){
        System.out.println("Study");
    }
}

1.3 Creation and use of objects

  • The format in which the object is created:
    • Class name Object name= new class name ();
  • Format of calling member:
    • Object names. Member variables
    • Object name. Member method ();
  • Sample code:
package com.itheima.object1;

public class TestStudent {
    /*
        The format in which the object is created:
                Class name Object name= new class name ();
        Format of call member variable:
                Object name. Variable name
        Format for calling member methods:
                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 + class name)
        System.out.println(stu);
    }
}

1.4 Cases - Creation and Use of Mobile Class

Requirements: First define a mobile phone class, then define a mobile phone test class, complete the use of member variables and methods through objects in the mobile phone test class

Analysis:

  • Member variables: brand, price

  • Membership Method: Call, Text Message

  • Sample code:

package com.itheima.test1;

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

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

    public void sendMessage(){
        System.out.println("Mass SMS");
    }
}
package com.itheima.test1;

public class TestPhone {
    public static void main(String[] args) {
        // 1. Create Objects
        Phone p = new Phone();
        // 2. Assigning member variables
        p.brand = "rice";
        p.price = 2999;
        // 3. Print assigned member variables
        System.out.println(p.brand + "..." + p.price);
        // 4. Call member methods
        p.call("Aqiang");
        p.sendMessage();
    }
}

2. Object Memory Map

2.1 Single Object Memory Map [Understanding]

2.2 Multiple Object Memory Maps [Understanding]

  • Summary:

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

2.3 Multiple objects point to the same memory map [Understanding]

  • Summary:

    When references to multiple objects point to the same memory space (variables record the same address value)

    Any object that modifies data in memory is then modified data, regardless of which object is used for data acquisition.

3. Member variables and local variables

3.1 Differences between member variables and local variables

  • Different locations in a class: member variables (outside methods in a class) local variables (inside a method or on a method declaration)
  • Different location in memory: member variable (heap memory) local variable (stack memory)
  • Life cycle is different: member variables (exist with the object and disappear with the object) local variables (exist with the method call and disappear with the method call)
  • Initialization values are different: member variables (with default initialization values) local variables (no default initialization values, must be defined before assignment can be used)

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 privates can only be accessed in this class. For privately modified member variables, if needed by other classes, provide appropriate operations

Provides a "get variable name ()" method to get the value of a member variable, decorated with public

Provides a set variable name (parameter) method to set the value of a member variable, decorated with public

Sample code:

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

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

    public int getAge() {
        return age;
    }

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

4.2 Use of the private keyword

  • Requirements:

    • Define standard student classes Requiring name and age to be private ly decorated
    • It also provides set and get methods and show methods for displaying data easily
    • Create objects in the test class and use them. The final console outputs Lin Qingxia, 30
  • Sample code:

    /*
        Student Class
     */
    class Student {
        //Member variables
        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 Test Class
     */
    public class StudentDemo {
        public static void main(String[] args) {
            //create object
            Student s = new Student();
    
            //Assigning values to member variables using the set method
            s.setName("Lin Qingxia");
            s.setAge(30);
    
            s.show();
    
            //Get the value of a member variable using the get method
            System.out.println(s.getName() + "---" + s.getAge());
            System.out.println(s.getName() + "," + s.getAge());
    
        }
    }
    

4.3 this keyword [application]

Overview: this modifies variables used to refer to member variables, whose primary purpose is (to distinguish between renames of local and member variables)

  • If the parameter of a method has the same name as a member variable, variables without this modification refer to the parameter, not the member variable
  • Method parameter does not have the same name as member variable, variable without this modifier refers to 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 [Understanding]

  • Note: This represents a reference to the currently invoked method, and which object invokes the method, this represents which object

  • Illustration:

4.5 Encapsulation Ideas

  1. Overview of Packaging
    Is one of the three main object-oriented features (encapsulation, inheritance, polymorphism)
    Object-oriented programming language is the simulation of the objective world, in which member variables are hidden inside the object, the outside can not be directly manipulated
  2. Packaging principle
    Hide some information of the class inside the class, do not allow direct access by external programs, but use the methods provided by the class to operate on and access hidden information
    Member variable private, providing the corresponding getXxx()/setXxx() method
  3. Packaging benefits
    Methods to control the operation of member variables improve the security of the code
    Encapsulating code in a way improves code reuse

5. Construction methods

5.1 Format and timing of construction methods

  • Format Note:
    • The method name is the same as the class name, with the same case
    • No return value type, not even void
    • No specific return value (result data cannot be brought back by retrun)
  • Execution timing:
    • Called when an object is created, and the construction method is executed every time the object is created
    • Construction methods cannot be called manually
  • Sample code:
class Student {
    private String name;
    private int age;

    //Construction method
    public Student() {
        System.out.println("Parameterless 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 Role of construction methods

  • Used to initialize data (properties) of an object
package com.itheima.constructor;

public class Student {
    /*
        Format:

               1. The method name needs to be the same as the class name, with the same case
               2. No return value type, not even void
               3. No specific return value (return cannot bring back specific results)
     */

    private String name;
    private int age;

    // 1. If no construction method is written in a class, a default parameterless construction method will be provided
    public Student(){}

    // 2. If you manually write a construction method, 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 Class construction methods");
    }

    public void show(){
        System.out.println(name + "..." + age);
    }
}
package com.itheima.constructor;

public class TestStudent {
    public static void main(String[] args) {
        Student stu1 = new Student("Zhang San",23);
        stu1.show();

        Student stu2 = new Student();
    }
}

5.3 Notice for construction method

Creation of construction methods:

If no construction method is defined, a default parameterless construction method will be given

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

Creation of construction methods:

If no construction method is defined, a default parameterless construction method will be given. If a construction method is defined, the default construction method will no longer be provided.

Recommended usage:

Write parameterless and parameterized construction methods manually, whether you use them or not

5.4 Coding and use of standard classes

Code:

package com.itheima.test3;

/*
    JavaBean Class: Encapsulate 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);
    }
}

package com.itheima.test3;

public class TestStudent {
    public static void main(String[] args) {
        // 1. parameterless constructors create objects and assign member variables through the setXxx method
        Student stu1 = new Student();
        stu1.setName("Zhang San");
        stu1.setAge(23);
        stu1.show();

        // 2. Assigning attributes directly through parametric construction
        Student stu2 = new Student("Li Si",24);
        stu2.show();
    }
}

Topics: Java JavaSE encapsulation