2021-10-25 Java language foundation Day06

Today's content

1, Classes and objects

1. Overview of object-oriented thought

package cn.itcast.day06.demo01;

import java.util.Arrays;

/*
Process oriented: when a function needs to be implemented, each specific step should be handled in detail.
Object oriented: when I need to implement a function, I don't care about the specific steps, but find someone who already has the function to help me.
 */
public class Demo01PrintArray {

    public static void main(String[] args) {
        int[] array = { 10, 20, 30, 40, 50, 60 };

        // The required printing format is: [10, 20, 30, 40, 50]
        // Using process oriented, the details of each step should be done by yourself.
        System.out.print("[");
        for (int i = 0; i < array.length; i++) {
            if (i == array.length - 1) { // If it is the last element
                System.out.println(array[i] + "]");
            } else { // If not the last element
                System.out.print(array[i] + ", ");
            }
        }
        System.out.println("==============");

        // Using object orientation
        // Find a JDK to provide us with a good Arrays class,
        // There is a toString method, which can directly turn the array into a string of the desired format
        System.out.println(Arrays.toString(array));
    }

}

2. Examples of object-oriented ideas

give an example
wash clothes:

  • Facing the process: take off the clothes – > find a basin – > put some washing powder – > add some water – > soak for 10 minutes – > knead – > wash the clothes – > wring dry – > dry
  • Object oriented: take off clothes – > turn on the automatic washing machine – > throw clothes – > button – > hang them

difference

  • Process oriented: emphasize steps.
  • Object oriented: emphasize the object. The object here is the washing machine.

characteristic

  1. Object oriented thinking is an idea more in line with our thinking habits. It can simplify complex things and turn us from executor to commander.
  2. Object oriented language contains three basic features, namely encapsulation, inheritance and polymorphism.

3. Relationship between class and object

What is a class?

  • Class: a collection of related properties and behaviors. It can be regarded as the template of a kind of things, and the attribute characteristics and behavior characteristics of things are used to describe this kind of things.
    In reality, describe a class of things:
  • Attribute: is the state information of the thing.
  • Behavior: is what the thing can do.

Example: kitten.
Attributes: name, weight, age, color. Behavior: walk, run and shout.

What is an object?

  • Object: it is the concrete embodiment of a kind of things. An object is an instance of a class (an object is not looking for a girlfriend), and it must have the properties and behavior of such things.

In reality, an example of a kind of thing: a kitten.
Example: a kitten.
Attributes: tom, 5kg, 2 years, yellow. Behavior: sneaking around the wall, jumping and running, meowing.

Relationship between class and object

  • Class is the description of a class of things, which is abstract.
  • An object is an instance of a class of things and is concrete.
  • Class is the template of object, and object is the entity of class.

4. Definition of class

Comparison of things and classes

A class of things in the real world:
Attribute: state information of things
Behavior: what can things do

package cn.itcast.day06.demo01;

/*
Define a class to simulate "student" things. There are two components:

Attribute (what is):
    full name
    Age
 Behavior (what can be done):
    having dinner
    sleep
    study

Corresponding to Java classes:

Member variables (properties):
    String name; // full name
    int age; // Age
 Member method (behavior):
    public void eat() {} // having dinner
    public void sleep() {} // sleep
    public void study() {} // study

matters needing attention:
1. Member variables are defined directly in the class and outside the method.
2. Do not write static keyword for member methods.
 */
public class Student {

    // Member variable
    String name; // full name
    int age; // Age

    // Member method
    public void eat() {
        System.out.println("Eat!");
    }

    public void sleep() {
        System.out.println("Sleep!");
    }

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

}

5. Creation and use of objects

package cn.itcast.day06.demo01;

/*
Usually, a class cannot be used directly. You need to create an object according to the class before you can use it.

1. Guide Package: that is, indicate where the class to be used is located.
import Package name. Class name;
import cn.itcast.day06.demo01.Student;
If it belongs to the same package as the current class, the package guide statement can be omitted.

2. Create, format:
Class name object name = new class name ();
Student stu = new Student();

3. It can be used in two cases:
Use member variable: object name. Member variable name
 Use member method: object name. Member method name (parameter)
(That is, use the object name for whoever you want.)

matters needing attention:
If the member variable is not assigned, it will have a default value, and the rule is the same as that of array.
 */
public class Demo02Student {

    public static void main(String[] args) {
        // 1. Guide package.
        // The Student class I need to use is under the same package as my Demo02Student, so the package guide statement is omitted

        // 2. Create, format:
        // Class name object name = new class name ();
        // According to the Student class, an object named stu is created
        Student stu = new Student();

        // 3. Use the member variable in the format:
        // Object name. Member variable name
        System.out.println(stu.name); // null
        System.out.println(stu.age); // 0
        System.out.println("=============");

        // Change the value content of the member variable in the object
        // Assign the string on the right to the name member variable in the stu object
        stu.name = "Zhao Liying";
        stu.age = 18;
        System.out.println(stu.name); // Zhao Liying
        System.out.println(stu.age); // 18
        System.out.println("=============");

        // 4. Use the member method of the object. Format:
        // Object name. Member method name ()
        stu.eat();
        stu.sleep();
        stu.study();
    }

}

6. Mobile phone exercises

package cn.itcast.day06.demo02;

/*
Define a class to simulate "mobile phone" things.
Attributes: brand, price, color
 Behavior: making phone calls and sending text messages

Corresponding to class:
Member variables (properties):
    String brand; // brand
    double price; // Price
    String color; // colour
 Member method (behavior):
    public void call(String who) {} // phone
    public void sendMessage() {} // Mass texting
 */
public class Phone {

    // Member variable
    String brand; // brand
    double price; // Price
    String color; // colour

    // Member method
    public void call(String who) {
        System.out.println("to" + who + "phone");
    }

    public void sendMessage() {
        System.out.println("Mass texting");
    }
}

package cn.itcast.day06.demo02;

public class Demo01PhoneOne {

    public static void main(String[] args) {
        // According to the Phone class, create an object named one
        // Format: class name object name = new class name ();
        Phone one = new Phone();
        System.out.println(one.brand); // null
        System.out.println(one.price); // 0.0
        System.out.println(one.color); // null
        System.out.println("=========");

        one.brand = "Apple";
        one.price = 8388.0;
        one.color = "black";
        System.out.println(one.brand); // Apple
        System.out.println(one.price); // 8388.0
        System.out.println(one.color); // black
        System.out.println("=========");

        one.call("Steve Jobs"); // Call jobs
        one.sendMessage(); // Mass texting
    }

}

7. Memory map of an object

8. Memory diagram of two objects using the same method

9. Two references point to the memory map of the same object

10. Use the object type as the parameter of the method

11. Use the object type as the return value of the method

12. Differences between member variables and local variables

package cn.itcast.day06.demo03;

/*
Local and member variables

1. Different defined positions [key points]
Local variables: inside methods
 Member variable: written directly in the class outside the method

2. Different scope of action [ key ]
Local variable: it can only be used in the method, and it can't be used after the method
 Member variables: the entire class can be generic.

3. Different default values [ key ]
Local variable: there is no default value. If you want to use it, you must assign it manually
 Member variable: if there is no assignment, there will be a default value. The rule is the same as that of array

4. Memory location is different (understand)
Local variable: in stack memory
 Member variable: in heap memory

5. Different life cycles (understand)
Local variable: it is born as the method enters the stack and disappears as the method exits the stack
 Member variable: it is born as the object is created and disappears as the object is garbage collected
 */
public class Demo01VariableDifference {

    String name; // Member variable

    public void methodA() {
        int num = 20; // local variable
        System.out.println(num);
        System.out.println(name);
    }

    public void methodB(int param) { // The parameters of the method are local variables
        // Parameters are bound to be assigned when a method is called.
        System.out.println(param);

        int age; // local variable
//        System.out.println(age); //  It can't be used without assignment

//        System.out.println(num); //  Wrong writing!
        System.out.println(name);
    }

}

13. Encapsulation of three object-oriented features

package cn.itcast.day06.demo03;

/*
Three characteristics of object-oriented: encapsulation, inheritance and polymorphism.

Encapsulation in Java:
1. Method is a kind of encapsulation
2. The keyword private is also an encapsulation

Encapsulation is to hide some details from the outside world.
 */
public class Demo02Method {

    public static void main(String[] args) {
        int[] array = {5, 15, 25, 20, 100};

        int max = getMax(array);
        System.out.println("Maximum:" + max);
    }

    // Give me an array and I'll give you a maximum
    public static int getMax(int[] array) {
        int max = array[0];
        for (int i = 1; i < array.length; i++) {
            if (array[i] > max) {
                max = array[i];
            }
        }
        return max;
    }

}

14. Function and use of private keyword

package cn.itcast.day06.demo03;

/*
Problem Description: when defining the age of Person, unreasonable values cannot be prevented from being set.
Solution: modify the member variables to be protected with the private keyword.

Once private is used for decoration, it can still be accessed freely in this class.
But! Beyond the scope of this class, you can no longer access it directly.

Indirect access to private member variables is to define a pair of Getter/Setter methods

Must be called setXxx or getXxx naming convention.
For Getter, there can be no parameters, and the return value type corresponds to the member variable;
For Setter, there can be no return value. The parameter type corresponds to the member variable.
 */
public class Person {

    String name; // full name
    private int age; // Age

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

    // This member method is specifically used to set data to age
    public void setAge(int num) {
        if (num < 100 && num >= 9) { // If it is reasonable
            age = num;
        } else {
            System.out.println("Unreasonable data!");
        }
    }

    // This member method is specifically used to get the data of age
    public int getAge() {
        return age;
    }

}

package cn.itcast.day06.demo03;

public class Demo03Person {

    public static void main(String[] args) {
        Person person = new Person();
        person.show();

        person.name = "Zhao Liying";
//        person.age = -20; //  Direct access to private content, wrong writing!
        person.setAge(20);
        person.show();
    }

}

15. Practice using the private keyword to define student classes

package cn.itcast.day06.demo03;

/*
For boolean values in basic types, the Getter method must be written in the form of isXxx, while the setXxx rule remains unchanged.
 */
public class Student {

    private String name; // full name
    private int age; // Age
    private boolean male; // Are you a man

    public void setMale(boolean b) {
        male = b;
    }

    public boolean isMale() {
        return male;
    }

    public void setName(String str) {
        name = str;
    }

    public String getName() {
        return name;
    }

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

    public int getAge() {
        return age;
    }
}

package cn.itcast.day06.demo03;

public class Demo04Student {

    public static void main(String[] args) {
        Student stu = new Student();

        stu.setName("Lu Han");
        stu.setAge(20);
        stu.setMale(true);

        System.out.println("full name:" + stu.getName());
        System.out.println("Age:" + stu.getAge());
        System.out.println("Is it a man:" + stu.isMale());
    }

}

16. Function of this keyword

package cn.itcast.day06.demo04;

/*
When the local variable of the method and the member variable of the class have the same name, the local variable shall be used preferentially according to the "proximity principle".
If you need to access member variables in this class, you need to use the format:
this.Member variable name

"Whoever calls the method is this. "
 */
public class Person {

    String name; // My own name

    // Parameter name is the name of the opposite party
    // The member variable name is its own name
    public void sayHello(String name) {
        System.out.println(name + ",Hello. I am" + this.name);
        System.out.println(this);
    }

}

package cn.itcast.day06.demo04;

public class Demo01Person {

    public static void main(String[] args) {
        Person person = new Person();
        // Set my own name
        person.name = "Wang Jianlin";
        person.sayHello("Sephirex Wang");

        System.out.println(person); // Address value
    }

}

17. Construction method

package cn.itcast.day06.demo04;

/*
Construction method is a method specially used to create objects. When we create objects through the keyword new, we are actually calling the construction method.
Format:
public Class name (parameter type parameter name){
    Method body
}

matters needing attention:
1. The name of the constructor must be exactly the same as the name of the class, even the case
2. The constructor should not write the return value type, not even void
3. Constructor cannot return a specific return value
4. If no constructor is written, the compiler will give a constructor by default, and do nothing without parameters and method body.
public Student() {}
5. Once at least one constructor is written, the compiler will no longer give away.
6. Construction methods can also be overloaded.
Overload: the method name is the same, but the parameter list is different.
 */
public class Student {

    // Member variable
    private String name;
    private int age;

    // Parameterless construction method
    public Student() {
        System.out.println("The parameterless construction method is executed!");
    }

    // Construction method of all parameters
    public Student(String name, int age) {
        System.out.println("The full parameter construction method is implemented!");
        this.name = name;
        this.age = age;
    }

    // Getter Setter
    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;
    }

}

package cn.itcast.day06.demo04;

public class Demo02Student {

    public static void main(String[] args) {
        Student stu1 = new Student(); // Nonparametric structure
        System.out.println("============");

        Student stu2 = new Student("Zhao Liying", 20); // Fully parametric structure
        System.out.println("full name:" + stu2.getName() + ",Age:" + stu2.getAge());
        // If you need to change the data content of member variables in the object, you still need to use the setXxx method
        stu2.setAge(21); // Change age
        System.out.println("full name:" + stu2.getName() + ",Age:" + stu2.getAge());

    }

}

18. Define a standard class

package cn.itcast.day06.demo05;

/*
A standard class usually has the following four components:

1. All member variables should be decorated with the private keyword
2. Write a pair of child Getter/Setter methods for each member variable
3. Write a parameterless construction method
4. Write a full parameter construction method

Such standard classes are also called Java beans
 */
public class Student {

    private String name; // full name
    private int age; // 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;
    }
}

package cn.itcast.day06.demo05;

public class Demo01Student {

    public static void main(String[] args) {
        Student stu1 = new Student();
        stu1.setName("Delireba");
        stu1.setAge(20);
        System.out.println("full name:" + stu1.getName() + ",Age:" + stu1.getAge());
        System.out.println("=================");

        Student stu2 = new Student("Gulinaza", 21);
        System.out.println("full name:" + stu2.getName() + ",Age:" + stu2.getAge());
        stu2.setAge(22);
        System.out.println("full name:" + stu2.getName() + ",Age:" + stu2.getAge());
    }

}

Keywords: Java Back-end

Added by mark_h_uk on Sun, 07 Nov 2021 04:18:05 +0200