java foundation 9_ Class, object

Posted by bharrison89 on Mon, 07 Feb 2022 22:20:21 +0100

1 object oriented

summary

Object oriented thought is a kind of programming thought. Under the guidance of object-oriented thought, we use java language to design and develop computer programs. The object here generally refers to all things in the display, and each thing has its own attributes and behavior. The object-oriented idea is the design idea of abstracting the attribute characteristics and behavior characteristics of things with reference to real things in the process of computer programming and describing them as computer events. It is different from the oriented idea, which emphasizes that the function is realized by calling the behavior of the object, rather than operating and realizing it step by step.

Process oriented: when a function needs to be realized, each specific step should be handled in detail; Emphasize process
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 do things; Emphasize object

give an example:

wash clothes:
Facing the process: take off clothes - put in the basin - add water - soak - Wash - wring dry
Object oriented: take off clothes - put the washing machine

example:

package cn.itcast.day04.demo02;

import sun.plugin.javascript.navig.Array;

import java.util.Arrays;

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

        //Process oriented, dealing with every detail
        System.out.print("[");
        for (int i = 0; i < array.length; i++) {
            if(i == array.length-1){
                System.out.println(array[i] + "]");
            }else {
                System.out.print(array[i] + ",");
            }
        }

        System.out.println("=======");
        //Object oriented, directly use toString to convert the array into the string you want
        System.out.println(Arrays.toString(array));
    }
}

2. Classes and objects

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 attributes and characteristics of things are used to describe this kind of things

A description of things in reality:
Attribute: it is the state information of the thing
Behavior: is what the thing can do

Example: kitten
Attributes: name, weight
Behavior: walking and running

What is an object

Object: it is the concrete embodiment of a kind of things. An object is an instance of a class, which must have the properties and behavior of such things

In reality, an example of a class of things: cats

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

For example: mobile phone drawing - abstract, real mobile phone - concrete

3. 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

Things described by class in java:
Member variable: the attribute of the corresponding thing
Member method: the behavior of corresponding things

Class creation and use

public class ClassName{
//Member variable
//Member method
}

Member variable: in class, outside method
Member method: does not contain static

For example:

public class Stident{
//Member variable
String name;
int age;
//Member method
public void study{
System.out.println("study hard and make progress every day");
}

Use of class:

  1. Guide Package: indicates where the class needs to be used
    import package name Class name;
    If it belongs to the same package as the current class, you can omit the package guide statement without writing

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

3. Use
Use member variable: object name Member variable name
Use member method: object name Member method name (parameter)

public class DemoStudy {
    public static void main(String[] args) {
        Student stu = new Student();
        System.out.println(stu.age);
        System.out.println(stu.name);
        stu.eat();

        System.out.println("=====");
        //Change Student member variable value
        stu.age = 18;
        stu.name = "Gao Yuanyuan";
        System.out.println(stu.name);
        System.out.println(stu.age);
    }

}

Object memory graph

1. An object calls a method memory graph


The method running in the stack memory follows the principle of "first in first out, last in first out". The variable stu points to the space in the heap memory, looks for the information method and executes the method.

2. Memory map of two objects calling the same method

3. Two references point to the same object

Use the object type as the parameter of the method

public class Student {
    String name;
    int age;
    public void study(){
        System.out.println("study hard");
    }
    public void eat(){
        System.out.println("Eat well");
    }
}

public class TestStudent {
    public static void main(String[] args) {
        Student student = new Student();
        student.name = "Gao Yuanyuan";
        student.age = 18;
        method(student);
    }
    public static void method(Student stu){
        System.out.println(stu.age);
        System.out.println(stu.name);
    }
}

When an object is passed to a method as a parameter, what is actually passed in is the address value of the object

The memory diagram is as follows

Use object as method return value

public class Student {
    String name;
    int age;
    public void study(){
        System.out.println("study hard");
    }
    public void eat(){
        System.out.println("Eat well");
    }
}
public class MethodStudent {
    public static void main(String[] args) {
        Student stu = method();
        System.out.println(stu.name);
        System.out.println(stu.age);
    }
    public static Student method(){
        Student student = new Student();
        student.age = 18;
        student.name = "Liu Yifei";
        return student;
    }
}


When the object type is used as the return value of the method, the object address value is returned

Differences between member variables and local variables

  1. Different definition positions
    Local variables: inside the method;
    Member variable: written directly in the class outside the method

  2. Different scope of action
    Local variable: it can only be used in the method, and it can't be used again when the method is out
    Member variable: the whole class can be used universally

3. The default value is different
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. Different memory locations
Local variable: in stack memory
Member variable: in heap memory
5. Different declaration cycles
Local variable: it is born as the method goes into the stack and disappears as the method goes out of the stack
Member variable: it is born as the object is created and disappears as the object is garbage collected

public class Test1 {
    int age;
    public void method() {
        int name;
        System.out.println(age);
//        System.out.println(name); If the local variable is not initialized and assigned, an error is reported

    }
    public void methodB(int param){
        // The variable in the method parameter is a local variable, which must be assigned during the transfer process and can be called directly
        System.out.println(param);
        System.out.println(age);
//        System.out.println(name); Local variable, cannot be used
    }
}
  1. Member variables can be divided into:
    Instance properties (no static modification)
    Exists with the existence of instance properties
    Class attribute (static modifier)
    Exist with the existence of class
    Member variables do not need to be explicitly initialized, and the system will automatically initialize them by default

    Local variables can be divided into:
    Formal parameter (formal parameter)
    Effective in the whole method
    Method local variable (defined within the method)
    It is valid from the definition of this variable to the end of the method
    Code block local variables (defined within the code block)
    It is valid from the definition of this variable to the end of the code block
    In addition to formal parameters, local variables must display initialization, that is, specify an initial value, otherwise they cannot be accessed.

code:

public class Person {
    String name;//Member variables and instance attributes exist with the existence of the instance, which can be called directly or used directly name
                //This is the reference of the current object (the instantiated object that actually calls this method), and person = new person(); This is equivalent to person
    static int age =10;//Class attribute exists with the existence of the class, and the class name can be used directly age
    void testMethod(){
        System.out.println(name);
        System.out.println(this.name);//This is the reference of the current object (the instantiated object that actually calls this method), and person = new person(); This is equivalent to person
        System.out.println(Person.age);
    }

}

For member variables and local variables, refer to the following:
https://www.cnblogs.com/zhengchenhui/p/5762966.html

private keyword

Once the member variable is decorated with the private keyword, it can be accessed freely in this class, but it cannot be accessed directly beyond the scope of this class;
Indirect access to private member variables is to define a pair of Getter/Setter methods;
Must be called setXxx or getXxxx naming rules
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

For the boolean value in the basic type, the Getter method must be written in the form of isXxxx, while setXxx remains unchanged

public class Person {
    String name;
    private int age;

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

    public void setAge(int num){
        if( num <= 100 && num > 0){
            age = num;
        }else {
            System.out.println("Unreasonable age parameters");
        }
    }
    public int getAge(){
        return age;
    }
}

public class TestPerson {

    public static void main(String[] args) {
        Person person = new Person();
        person.setAge(50);
        person.name = "Lao Liu";
        person.show();
    }
}

this keyword

When local variables and class variables have the same name, local variables are preferred according to the principle of proximity;
If you need to access the member variables in this class, you need to use the format: this Member variable

Whoever calls the method is this

return this is to return the reference of the current object (the instantiated object that actually calls this method), such as person = new person(); This is equivalent to person

public class Person {
    String name;//Member variables and instance attributes exist with the existence of the instance, which can be called directly or used directly name
                //This is the reference of the current object (the instantiated object that actually calls this method), and person = new person(); This is equivalent to person
    static int age =10;//Class attribute exists with the existence of the class, and the class name can be used directly age

    void sayHello(String name){
        System.out.println(name + " Hello" + ". I am: " + this.name);
        System.out.println(Person.age);
        System.out.println("this Address value for:" + this);
    }
    void testMethod(){
        System.out.println(name);
        System.out.println(this.name);//This is the reference of the current object (the instantiated object that actually calls this method), and person = new person(); This is equivalent to person
        System.out.println(Person.age);
    }

}

public class TestPerson {

    public static void main(String[] args) {
        Person person = new Person();
        person.name = "Sephirex Wang";
        person.sayHello("Gentle");
        System.out.println("person Address value" + person);
    }
}

peron and this are both address values and are the same

Construction method

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 viod
3. The constructor cannot return a specific return value
4. If no construction method is written, the compiler will give a construction method by default. There are no parameters, method body and nothing to do with public Student() {}
5. Once at least one constructor is written, the compiler will no longer give away
6. The construction method can be overloaded
Overload: the method name is the same, but the parameter list is different

public class Student {

    private String name;
    private int age;
    //Parameterless constructor
    public Student(){
        System.out.println("Parameterless constructor");
    }
    //There is a parameter constructor, which can replace getter and setter at a certain level
    public Student(String name, int age){
        System.out.println("Parameterized constructor");
        this.name = name;
        this.age = age;
    }
    void setName(String str){
        name = str;
    }
    String getName(){
        return name;
    }

    void setAge(int num){
        age = num;
    }
    int getAge(){
        return age;
    }


}

public class TestStudent {
    public static void main(String[] args) {
        Student stu  = new Student(); //Parameterless construction, print out: parameterless constructor
        Student stu1 = new Student("Zhao Liying",18);//Execute the constructor with parameters and print out: constructor with parameters
        System.out.println("full name: " + stu1.getName() + " Age: " + stu1.getAge()); //Name: Zhao Liying age: 18
        stu1.setName("Lao Liu");  //It can still be changed through getter and setter
        stu1.setAge(22);
        System.out.println("full name: " + stu1.getName() + " Age: " + stu1.getAge());//Name: Lao Liu age: 22

    }

}

Topics: Java