1. Classes and objects

** Comparison of object-oriented and procedural ideas: **

** Process oriented: ** is a process-centric programming philosophy, the realization of every step of the function is self-implementation

** Object-oriented: ** is an object – centric programming philosophy, by directing objects to achieve specific functions

1.1 Relationship between classes and objects

Objective things are objects, so we often say that everything is objects.

  • class
    • The understanding of the class
      • A class is an abstraction of a class of things in real life that share common properties and behavior
      • A class is the data type of an object. A class is a collection of objects with the same properties and behavior
      • Simple understanding: a class is a description of something real
    • The composition of the class
      • Attribute: Refers to the characteristics of something, such as a mobile phone (brand, price, size)
      • Behavior: The actions that something can perform, e.g., something on a phone (making a call, sending a text message)
  • Relationships between classes and objects
    • Class: A class is an abstraction of a class of things in real life that share common properties and behavior
    • Object: a real entity that can be seen and touched
    • Simple understanding: a class is a description of a thing, and an object is a concrete thing

1.2 Definition of Class [Application]

The composition of a class is made up of two parts: attributes and behaviors

  • ** Attribute: ** To be represented in a class by a member variable (outside of a method in a class)
  • ** behavior: ** is represented by a member method in the class (remove the static keyword compared to the previous method).

Class definition steps:

1) define the class

② Write the member variables of the class

③ Write the member methods of the class

public class Student {
    // Attributes: name, age
    // Member variables: The same format as before, but in a different location, outside the class method
    String name;
    int age;

    // Behavior: learning
    // Member methods: The same format as before, but with the static keyword removed.
    public void study(a){
        System.out.println("Learning"); }}Copy the code

1.3 Object creation and use

  • Create object format:
    • Class name Object name = new class name ();
  • The format of the call member:
    • Object name. Member variable
    • Object name. Member method ();
  • ** Example code: **
public class TestStudent {
    Object name = new class name (); Call a member variable in the format of the object name. A variable name calls a member method in the form of an object name. The 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";
        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); }}Copy the code

1.4 Case – Creation and use of mobile phone class

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

Analysis:

  • Member variables: brand, price
  • Membership methods: call, send text messages
  • Sample code:
public class Phone {
    // Brand, price
    String brand;
    int price;

    // Make phone calls and send text messages
    public void call(String name){
        System.out.println("To"+name+"Make a call");
    }

    public void sendMessage(a){
        System.out.println("Group texting"); }}Copy the code
public class TestPhone {
    public static void main(String[] args) {
        // 1. Create objects
        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 the member method
        p.call("Strong"); p.sendMessage(); }}Copy the code

2. Object memory diagram

2.1 Memory map of a single object

2.2 Memory map of multiple objects

  • Conclusion:

    Multiple objects in the heap memory, have different memory partition, member variables stored in their own memory area, member method multiple objects share a share

2.3 Multiple Objects pointing to the same Memory graph

  • Conclusion:

    When multiple object references refer to the same memory space (the address values recorded by variables are the same)

    Any object that modifies the data in memory is the modified data, regardless of which object is subsequently used to retrieve the data.

  • The garbage collection

    • Note: When an address generated by an object or array in heap memory cannot be found by any means, it is judged to be “garbage” in memory. Garbage is passed to the Java garbage collector and cleaned up automatically when it is idle.

3. Member and local variables

  • What about member variables and local variables
    • Member variables: Variables outside methods in a class
    • Local variables: variables in a method

3.1 Differences between member variables and local variables

  • ** Member variables (outside of a method in a class) local variables (inside a method or on a method declaration)
  • ** Different locations in memory: ** Member variables (heap memory) local variables (stack memory)
  • ** Different life cycles: ** member variables (exist with the object, disappear with the object disappears) local variables (exist with the method call, drunk method call is finished and disappear)
  • ** Different initializers: ** Member variables (with default initializers) local variables (without default initializers, must be defined first, 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)

A member modified by private can only be accessed in this class. If a member variable modified by private needs to be used by other classes, the corresponding operation is provided

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

Provides a “set variable name (parameter)” method that sets the value of a member variable. The method is public

Sample code:

/* Student */
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 gave me the wrong age.");
        } else{ age = a; }}public int getAge(a) {
        return age;
    }

    // Member methods
    public void show(a) {
        System.out.println(name + ","+ age); }}/* Student tests */
public class StudentDemo {
    public static void main(String[] args) {
        // Create an object
        Student s = new Student();
        // Assign a value to a member variable
        s.name = "Brigitte Lin";
        s.setAge(30);
        Call the show methods.show(); }}Copy the code

4.2 Use of the private keyword

  • Requirements:

    • Define a standard student class that requires name and age to be private
    • It also provides set and GET methods and a show method for displaying data
    • Test class to create objects and use, the final console output Brigitte Lin, 30
  • Sample code:

    /* Student */
    class Student {
        // Member variables
        private String name;
        private int age;
    
        / / get/set methods
        public void setName(String n) {
            name = n;
        }
    
        public String getName(a) {
            return name;
        }
    
        public void setAge(int a) {
            age = a;
        }
    
        public int getAge(a) {
            return age;
        }
    
        public void show(a) {
            System.out.println(name + ","+ age); }}/* Student tests */
    public class StudentDemo {
        public static void main(String[] args) {
            // Create an object
            Student s = new Student();
    
            // Assign a value to a member variable using the set method
            s.setName("Brigitte Lin");
            s.setAge(30);
    
            s.show();
    
            // Use the get method to get the value of a member variable
            System.out.println(s.getName() + "-" + s.getAge());
            System.out.println(s.getName() + ","+ s.getAge()); }}Copy the code

4.3 This keyword [Application]

Summary: This modifier is used to refer to member variables. Its main function is to distinguish local variables from member variables.

  • If a method parameter has the same name as a member variable, variables without the this modifier refer to the parameter, not the member variable
  • Method parameters do not have the same name as member variables; variables without this are member variables

Code implementation:

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

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

    public String getName(a) {
        return name;
    }

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

    public int getAge(a) {
        return age;
    }

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

4.4 Principle of this memory

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

  • Illustration:

4.5 Encapsulating ideas

  1. Encapsulation overview is one of the three characteristics of object-oriented (encapsulation, inheritance, polymorphism). It is the simulation of the objective world by object-oriented programming language. In the objective world, member variables are hidden inside the object, and the outside world cannot operate directly

    (Hide implementation details and expose only the common access method — the plugboard)

  2. The encapsulation principle hides some information of a class inside the class and does not allow external programs to access it directly. Instead, the class provides methods to operate on the hidden information and access the member variable private, providing the corresponding getXxx()/setXxx() methods

  3. Encapsulation benefits The operation of member variables is controlled by methods, which improves code security. The code is encapsulated by methods, which improves code reuse

  4. Common embodiment of encapsulation:

    1. A private member variable that provides setXxx and getXxx methods
    2. Extract code into a method, which is an encapsulation of the code
    3. Attributes are extracted into classes, which encapsulate the data

5. Construction method

5.1 Constructor format and execution timing

  • Note the format:
    • The method name must be the same as the class name and case must be the same
    • There is no return value type, not even void
    • No concrete return value (cannot be returned by retrun)
  • Execution time:
    • Called when an object is created, and the constructor is executed each time an object is created
    • Constructors cannot be called manually
  • Sample code:
class Student {
    private String name;
    private int age;

    // constructor
    public Student(a) {
        System.out.println("Parameterless construction method");
    }

    public void show(a) {
        System.out.println(name + ","+ age); }}/* Test class */
public class StudentDemo {
    public static void main(String[] args) {
        // Create an object
        Student s = newStudent(); s.show(); }}Copy the code

5.2 Function of constructors

  • Used to initialize the data (attributes) of an object
public class Student {
    /* Format: 1. The method name must be the same as the class name and case must be the same. There is no return type, even void. 3. There is no concrete return value */

    private String name;
    private int age;

    // 1. If no constructor is written in a class, a default no-argument constructor is provided
    public Student(a){}

    // 2. If you write the constructor manually, the system will no longer provide the default no-argument constructor
    public Student(String name, int age){
        this.name = name;
        this.age = age;
        System.out.println("I'm the constructor of the Student class.");
    }

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

        Student stu2 = newStudent(); }}Copy the code

5.3 Precautions for construction methods

Constructor creation:

If no constructor is defined, a default no-argument constructor is given

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

Constructor creation:

If no constructor is defined, the system will give a default no-argument constructor. If a constructor is defined, the system will no longer provide the default constructor

Recommended usage:

Both no-argument constructors and parameterized constructors are written manually, whether used or not

5.4 Code writing and use of standard classes

Code:

/* JavaBean classes: encapsulate data */
public class Student {
    private String name;
    private int age;

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

    public String getName(a) {
        return name;
    }

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

    public int getAge(a) {
        return age;
    }

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

    public void show(a){
        System.out.println(name + "..."+ age); }}Copy the code
public class TestStudent {
    public static void main(String[] args) {
        // 1. Create an object with no argument constructor, and use setXxx to assign a value to a member variable
        Student stu1 = new Student();
        stu1.setName("Zhang");
        stu1.setAge(23);
        stu1.show();

        // 2. Assign a value directly to the attribute using the parameter constructor
        Student stu2 = new Student("Bill".24); stu2.show(); }}Copy the code