Java object-oriented, class definition, use of objects

Overview

  • Java language is an object-oriented programming language, and object-oriented thinking is a kind of programming thinking. Under the guidance of object-oriented thinking, we use Java language to design and develop computer programs. The object here refers to all things in reality, and each thing has its own attributes and behaviors. Object-oriented thinking is to refer to things in reality in the process of computer programming, abstract the attributes and behaviors of things, and describe them as computer events. It is different from the process-oriented thinking, which emphasizes the realization of the function by calling the behavior of the object, rather than the step-by-step operation.

For example

  • Washing clothes: process-oriented: take off the clothes -> find a basin -> put some washing powder -> add some water -> soak for 10 minutes -> knead -> wash the clothes -> wring dry -> air it.
    Object-oriented: Take off the clothes -> turn on the fully automatic washing machine -> throw the clothes -> button -> hang up

    • the difference:

      • Process-oriented: Emphasize steps.
      • Object-oriented: Emphasize the object, the object here is the washing machine.

Features

  • Object-oriented thinking is a kind of thinking that is more in line with our thinking habits. It can simplify complex things and transform us from executors to commanders. The object-oriented language contains three basic characteristics, namely encapsulation, inheritance and polymorphism.

Classes and objects

Looking around, you will find many objects, such as tables, chairs, classmates, teachers, etc. Tables and chairs belong to office supplies, and teachers and students are all human beings. So what is a class? What is an object?

  • In reality, describe a class of things:

    Attribute: It is the status information of the thing.
    Behavior: what the thing can do.

  • Example: cat.

    Attributes: name, weight, age, color.
    Behavior: walking, running, calling

What is an object

  • Object: It is the concrete embodiment of a class of things. An object is an instance of a class (the object is not to find a girlfriend), and it must have the attributes and behaviors of that type of thing.

  • In reality, an instance of a class of things: a kitten.

  • Example: a kitten.
    Attributes: tom, 5kg, 2 years, yellow.
    Behaviours: walking around the wall, jumping and running, meowing.

The relationship between class and object

  • Class is a description of a class of things and is abstract.
  • Objects are instances of a class of things and are concrete.
  • The class is the template of the object, and the object is the entity of the class.

Insert picture description here

Comparison of things and classes

  • A class of things in the real world:

    1. Attributes: the status information of things.
    2. Behavior: What things can do.
  • The same is true for describing things with class in Java:

    1. Member variables: corresponding to the properties of things
    2. Member method: corresponding to the behavior of things,
      class definition format
public class ClassName/*类名*/ {
    
       
    //成员变量   
    //成员方法  
}
  • Definition class : It is to define the members of the class, including member variables and member methods .
  • Member variable : It is almost the same as the previously defined variable. Only the location has changed. **In the class, outside the method.
  • Member method : It is almost the same as the previously defined method. Just remove static, the role of static will be explained in detail after object-oriented.
  • Example of class definition format: create a Student.java
public class Student {
    
        
    //成员变量       
    String name;//姓名        
    int age;//年龄
    //成员方法     
    //学习的方法     
    public void study() {
    
         
        System.out.println("好好学习,天天向上");   
    }     
    //吃饭的方法   
    public void eat() {
    
         
        System.out.println("学饿了要吃饭");   
    } 
}

Object format

  • Create an object:

    • Class name object name = new class name();
  • Use objects to access members of a class:

    • Object name. Member variable;
    • Object name. Member method ();
  • Example of object usage format: Create another Test01_Student.java

public class Test01_Student {
    
       
    public static void main(String[] args) {
    
         
        //创建对象格式:类名 对象名 = new 类名();     
        Student s = new Student();//使用上面创建的Student.java     
        System.out.println("s:"+s); //地址值       
        //直接输出成员变量值,是它们的默认值     
        System.out.println("姓名:"+s.name); //null     
        System.out.println("年龄:"+s.age); //0     
        System.out.println("‐‐‐‐‐‐‐‐‐‐");       
        //给成员变量赋值     
        s.name = "迪丽热巴";     
        s.age = 18;       
        //再次输出成员变量的值     
        System.out.println("姓名:"+s.name); //迪丽热巴     
        System.out.println("年龄:"+s.age); //18     
        System.out.println("‐‐‐‐‐‐‐‐‐‐");       
        //调用成员方法     
        s.study(); // 好好学习,天天向上    
        s.eat(); // 学饿了要吃饭  
    } 
}
type of data Defaults
Basic data types (four types and eight types) Integer (byte, short, int, long) 0
Floating point number (float, double) 0.0
Character (char) ‘\u0000’
Boolean false
Reference data type Array, class, interface null

Class and object exercises

  • Define the phone class: Phone.java
public class Phone {
    
       
    // 成员变量   
    String brand; //品牌   
    int price; //价格   
    String color; //颜色     
    // 成员方法   
    //打电话   
    public void call(String name) {
    
         
        System.out.println("给"+name+"打电话");   
    }     
    //发短信   
    public void sendMessage() {
    
         
        System.out.println("群发短信");   
    } 
}
  • Define the test class: Test02Phone.java
public class Test02Phone {
    
       
    public static void main(String[] args) {
    
         
        //创建对象     
        Phone p = new Phone();       
        //直接输出成员变量值,是它们的默认值     
        System.out.println("品牌:"+p.brand);//null     
        System.out.println("价格:"+p.price);//0     
        System.out.println("颜色:"+p.color);//null

        System.out.println("‐‐‐‐‐‐‐‐‐‐‐‐");
        //给成员变量赋值     
        p.brand = "锤子";     
        p.price = 2999;     
        p.color = "棕色"; 

        //再次输出成员变量值     
        System.out.println("品牌:"+p.brand);//锤子     
        System.out.println("价格:"+p.price);//2999    
        System.out.println("颜色:"+p.color);//棕色     
        System.out.println("‐‐‐‐‐‐‐‐‐‐‐‐");

        //调用成员方法     
        p.call("紫霞");//给紫霞打电话     
        p.sendMessage();//群发短信  
    } 
 }

Object call memory graph

An object, calling a method memory graph
Insert picture description here
Through the above figure, we can understand that the method running in the stack memory follows the principle of "first in, last out, last in, first out". The variable p points to the space in the heap memory, looking for method information, to execute the method.
However, there are still problems. When creating multiple objects, if each object saves a copy of the method information, it is a waste of memory, because the method information of all objects is the same. So how to solve this problem? Please see the diagram below.

Two objects call the same method memory graph When the
Insert picture description here
object calls a method, go to the class to find method information according to the method tag (address value) in the object. In this way, even for multiple objects, only one copy of method information is saved, saving memory space.
That is, Phone.class can be used multiple times but only saved once

A reference is passed as a parameter to the memory graph in the method. The
Insert picture description here
reference type is used as a parameter, and the address value is passed.
p is the Phone object. After assigning a value, passing p actually passes its address value, so it can naturally get the value in it

The difference between member variables and local variables
Variables are named differently according to their definition positions. As shown below:
Insert picture description here

  1. The position in the class is different: (emphasis)
  • Member variables: in the class, outside the method
  • Local variables: in the method or on the method declaration (formal parameters)
  1. The scope of action is different: (emphasis)
  • Member variables: in the class
  • Local variables: method
  1. The difference in initialization value: (emphasis)
  • Member variables: have default values
  • Local variable: There is no default value. Must be defined, assigned, and finally used
  1. The location in memory is different: (understand)
  • Member variable: heap memory
  • Local variables: stack memory
  1. Different life cycles: (understand)
  • Member variables: exist as the object is created, and disappear as the object disappears
  • Local variables: exist as the method is called, and disappear as the method is called

Package overview

Object-oriented programming language is a simulation of the objective world. In the objective world, member variables are hidden inside the object and cannot be directly manipulated or modified by the outside world. Encapsulation can be considered as a protective barrier to prevent the code and data of this class from being randomly accessed by other classes. To access this type of data, you must pass a specified method. Proper encapsulation can make the code easier to understand and maintain, and it also enhances the security of the code.

in principle

  • Hide the properties, if you need to access a property, provide a public method to access it.

Encapsulation steps

  1. Use the private keyword to modify member variables.
  2. Provide a pair of getXxx methods and setXxx methods for the member variables that need to be accessed.

The meaning of private

  1. Private is a permission modifier, representing the minimum permission.
  2. You can modify member variables and member methods.
  3. Member variables and member methods modified by private can only be accessed in this class.

Private usage format

  • Private data type variable name;
  1. Use private to modify member variables, the code is as follows:
public class Student {
    
       
    private String name;   
    private int age; 
}
  1. Provide getXxx method/setXxx method to access member variables, the code is as follows:
public class Student {
    
       
    private String name;   
    private int age;     
    public void setName(String n) {
    
         
        name = n;   
    }     
    public String getName() {
    
         
        return name;   
    }     
    public void setAge(int a) {
    
         
        age = a;   
    }     
    public int getAge() {
    
         
        return age;   
    } 
}

Packaging optimization 1-this keyword

  • We found that the formal parameter names in the setXxx method do not meet the requirements of the name-knowledge, so if the modification is consistent with the member variable name, will it be the same? code show as below:
public class Student {
    
       
    private String name;   
    private int age;   
    public void setName(String name) {
    
         
        name = name;   
    }     
    public void setAge(int age) {
    
         
        age = age;   
    } 
}
  • After modification and testing, we found a new problem, the member variable assignment failed. In other words, after modifying the formal parameter variable name of setXxx(), the method did not assign a value to the member variable! This is because the name of the formal parameter variable and the name of the member variable are the same, which causes the member variable name to be hidden . The variable name in the method cannot access the member variable, and the assignment fails. Therefore, we can only use this keyword to solve this duplication problem.

the meaning of this

  • This represents the reference (address value) of the current object of the class, that is, the object's own reference.

Remember: which object the method is called, this in the method represents that object. That is, who is calling, this represents who.

this format

  • this. member variable name;
  • Use this to modify the variables in the method to solve the problem of member variables being hidden. The code is as follows:
public class Student {
    
       
    private String name;   
    private int age;     
    public void setName(String name) {
    
         
        //name = name;     
        this.name = name;   
    }     
    public String getName() {
    
         
        return name;   
    }     
    public void setAge(int age) {
    
         
        //age = age;     
        this.age = age;   
    }     
    public int getAge() {
    
    
        return age;
    }
}

When there is only one variable name in the method, it is also modified by default, which can be omitted.

Packaging optimization 2-construction method

  • When an object is created, the constructor is used to initialize the object and assign initial values ​​to the member variables of the object.

Regardless of whether you customize the constructor or not, all classes have a constructor, because Java automatically provides a parameterless constructor. Once you define the constructor, the default parameterless constructor automatically provided by Java will become invalid.

Definition format of construction method

修饰符 构造方法名(参数列表){ 
    // 方法体      
}
  • In the way of writing the construction method, the method name is the same as the name of the class it is in. It has no return value, so it does not need a return value type, or even void. After using the constructor, the code is as follows:
public class Student {
    
       
    private String name;   
    private int age;   
    // 无参数构造方法   
    public Student() {
    
    }    
    // 有参数构造方法   
    public Student(String name,int age) {
    
         
        this.name = name;     
        this.age = age;    
    } 
}

Precautions

  1. If you do not provide a construction method, the system will give a parameterless construction method.
  2. If you provide a construction method, the system will no longer provide a parameterless construction method.
  3. The construction method can be overloaded, either with or without parameters.

Standard code-JavaBean

  • JavaBean is a standard specification for classes written in the Java language . A class conforming to JavaBean requires that the class must be concrete and public, and have a parameterless construction method, and provide set and get methods for manipulating member variables.
public class ClassName{
    
       
    //成员变量   
    //构造方法   
    //无参构造方法【必须】   
    //有参构造方法【建议】   
    //成员方法       
    //getXxx()   
    //setXxx() 
}
  • Write a class that conforms to the JavaBean specification. Take the student class as an example. The standard code is as follows:
public class Student {
    
       
    //成员变量   
    private String name;   
    private int age;     
    //构造方法   
    public Student() {
    
    }     
    public Student(String name,int age) {
    
         
        this.name = name;     
        this.age = age;   
    }     
    //成员方法   
    publicvoid setName(String name) {
    
         
        this.name = name;   
    }     
    public String getName() {
    
         
        return name;   
    }     
    publicvoid setAge(int age) {
    
         
        this.age = age;   
    }     
    publicint getAge() {
    
         
        return age;   
    } 
}
  • The test class, the code is as follows:
public class TestStudent {
    
       
    public static void main(String[] args) {
    
         
        //无参构造使用     
        Student s= new Student();     
        s.setName("柳岩");     
        s.setAge(18);     
        System.out.println(s.getName()+"‐‐‐"+s.getAge());
        //带参构造使用     
        Student s2= new Student("赵丽颖",18);          
        System.out.println(s2.getName()+"‐‐‐"+s2.getAge());   
    } 
}

Guess you like

Origin blog.csdn.net/qq_41076577/article/details/108183201