Java series tutorial day09 - object oriented

day09 -- object oriented

Outline:

1,object-oriented
2,Classes and objects
3,Method overload
4,Construction method
5,this keyword
6,Anonymous object
7,task

  Add Qianqian teacher vx to get the latest information    


1, Object oriented

1.1 what is object-oriented in life

Wash clothes and eat
 Process oriented: the focus is the process -- Thinking and doing things from the perspective of an executor
  //Step 1. Find a basin
  //Step 2. Collect clothes to be washed
  //Step 3. Put water and washing powder..
  //Step 4: Wash
  //Step 5: drying
​
Object oriented: the focus is the object -- from the perspective of the commander
  //step1: find an object
  //Step 2: let him wash clothes
  
  
Object oriented in life: find the right person and do the right thing..
Facing the process in life: do it yourself, follow the process steps, step by step, whistling...
​
In the code:
  Arrays class
    sort();-->sort
    binarySearch();-->search
  Scanner class
    sc.nextInt();
    sc.next();
    sc.nextDouble();


1.2 object oriented and process oriented

object-oriented:(OOP)
  Not a language, but a programming idea.
  Object oriented programming:(Object Oriented Programming)
    Object: object
    Oriented: Orientation
    Programming: program
    
Process oriented:
  Focus on the process(step)
  step1,step2,step3.. . . . 
  Summation analysis can be realized according to steps.
​
object-oriented:
  Focus on objects
    Everything is an object.
  A: Analyze the objects involved in the current problem domain.
  B: What features and functions do these objects have.
    External features: static attributes
    Action behavior: dynamic attributes
  C: Objects and relationships between objects.
    Inheritance relationship, aggregation relationship, association relationship...
    
    Stacking of classes.


2, Classes and objects

2.1 classes and objects

Class: actually refers to the category. A general term for the same kind of things. Describe such things,--->establish class
 Is an abstract concept.
Object:
 Class, which exists objectively and can be used. Individual.

How to define a class?

  • There should be external features that can describe this category - we call attributes (static attributes)
    Variables. (noun)
  • There should be a function that can describe the behavior of this category - we call it a method (dynamic attribute)
    Method is OK. (verb)

2.2 format of classes defined in Java

/*
class ClassName{//Class name initial capital
  //Attribute descriptions: external features
  //Behavior Description: what can you do
}
*/
requirement:
    1,CLassName It is required to comply with the hump naming method, with the initial capital, see the meaning of the name.
    2,Attribute description: external features, which are used to describe some features of this category, and these features pass through a"Words"To describe clearly, such as name and age. Use variables to represent—— [member variable] Field,word meaning"field"
    3,Behavior Description: what can be done is used to describe some behavior functions of this category, and these behavior functions are an action behavior, such as eating and sleeping. Use methods to represent—— [member method] Method,word meaning"method"
      Don't add static. 

Method: it is a piece of code with independent functions.

2.2.1 step 1 declaration class

public class Person{//Class name
​
}


2.2.2 [member variable] in step 2 declaration class

public class Person {
  //Step 2: member variable
  String name;//Use the variable name of String type to represent the name in human
  
  int age;//Age, a variable of type int, is used to represent age in humans
  
  char sex;//The variable sex of char type is used to represent the gender in humans
  
  
}


2.2.3 member method in Step3 declaration class

public class Person {
  //Step 2: member variable
  String name;//Use the variable name of String type to represent the name in human
  
  int age;//Age, a variable of type int, is used to represent age in humans
  
  char sex;//The variable sex of char type is used to represent the gender in humans
  
  //step3: member method
  public void eat(){
    System.out.println("time to have a meal..");
  }
  
  public void sleep(){
    System.out.println("Go to bed..");
  }
  
  public void daDouDou(){
    System.out.println("Beat beans...");
  }
}
​

2.3 object of class

2.3.1 creating class objects

Creating objects is also called instantiation of classes. Object, also known as an instance of a class.

/*
new keyword
new,Meaning: new, new
new Keyword for creating new objects.
*/
Scanner sc = new Scanner();//Scanner is also a class, and Person is also a class.
int[] arr = new int[5];
​
Syntax structure:
/*
Class name object name = new class name ();
*/
Person p1 = new Person();

Step 2: instantiate the object according to the class

Step 1: create class


2.3.2 accessing properties through objects

/*
int[] arr = new int[5];
Get the length of the array:
arr.length
arr Length of
*/
Syntax of object access property: it is a.
//Assign values to the properties of the object
p1.name = "Wang Ergou";//Assign p1 the value to the name attribute of this object
p1.age = 18;
p1.sex = 'male';
​
​
//Gets the property value of the object
System.out.println("full name:"+p1.name);
System.out.println("Age:"+p1.age);
System.out.println("Gender:"+p1.sex);


2.3.3 object access method

/*
Scanner sc = new Scanner();
sc.nextInt();
*/
Scanner,Just one class,A class
sc,Is based on Scanner An object created
​
Object calls methods in the class, syntax, and so on.
object.Method name();
p1.eat();
p1.sleep();
p1.daDouDou();


2.3 memory analysis

Example code:

package com.qf.demo01;
​
public class Test1Person {
​
  public static void main(String[] args) {
    //Step 1: create an object of the Person class
    //Syntax: class name object name = new class name ();
    
    Person p1 = new Person();
    System.out.println(p1);//Print the value of p1, which is the reference type, and print the address of the object pointed to by p1.
    
    System.out.println(p1.name);
    System.out.println(p1.age);
    System.out.println(p1.sex);
    
    
    
    
    /*
     * com.qf.demo01.Person@15db9742
     * Package name. Class name @ encoding value ----- > is understood as the memory address of p1.
     * 
     * java Data types in:
     *  Basic types: byte, short, char, int, long, bolean, float, double
     *  Reference type:
     *      Array, class type
     * 
     */
    //Step 2: access attributes through objects. The syntax is
    //Assign values to the properties of the object
    p1.name = "Wang Ergou";//Assign p1 the value to the name attribute of this object
    p1.age = 18;
    p1.sex = 'male';
    
    
    //Gets the property value of the object
    System.out.println("full name:"+p1.name);
    System.out.println("Age:"+p1.age);
    System.out.println("Gender:"+p1.sex);
    
    
    //step3: accessing member methods through objects -- > is understood as calling member methods through objects
    p1.eat();
    p1.sleep();
    p1.daDouDou();
    
    
  }
​
}
​

Memory analysis diagram


Example code:

package com.qf.demo01;
​
public class Test2Person {
​
  public static void main(String[] args) {
    //1. Create an object of Person class
    Person p1 = new Person();
    System.out.println(p1);//Memory address of p1: com.qf.demo01 Person@15db9742
    
    p1.name = "Zhang Sangou";
    p1.age = 19;
    p1.sex = 'male';
    
    System.out.println(p1.name);//Zhang Sangou
    System.out.println(p1.age);//19
    System.out.println(p1.sex);//male
          
    //2. Create another object of Person class
    
    Person p2 = new Person();
    System.out.println(p2);//Memory address of p2, com.qf.demo01 Person@6d06d69c
    
    p2.name = "Li Xiaohua";
    p2.age = 17;
    p2.sex = 'female';
    
    System.out.println(p2.name);//Li Xiaohua
    System.out.println(p2.age);//17
    System.out.println(p2.sex);//female
      
    //3.
    Person p3 = null;//Only the Person type object p3 is declared, but in fact, no real object is created in heap memory.
    
    /*
     * NullPointerException,Null pointer exception
     * 
     * The object does not exist, it is null,
     *  If you forcibly access an object's property or call a method, you will get a null pointer exception.
     */
    //System.out.println("---->"+p3.name);// Error reported: NullPointerException
    
    p3 = p1;//Assign the value of p1 (memory address of p1 object) to p3, and the result -- > p1 and p3 store the memory address of the same object.
    
    p3.name = "Li Tiezhu";
    System.out.println(p1.name);//Li Tiezhu
    System.out.println(p2.name);//Li Xiaohua
    System.out.println(p3.name);//Li Tiezhu
    
    Person p4 = new Person();
    System.out.println(p4);//?
    
    p4.name = "Wang Erya";
    p4.age = 18;
    p4.sex = 'female';
    System.out.println(p4.name );
    System.out.println(p4.age);
    System.out.println(p4.sex);
    
    p4 = p1;//If the memory address of the object is changed, it will no longer point to the original memory object.
    System.out.println(p1.name);
    System.out.println(p3.name);
    System.out.println(p4.name);
  }
​
}
​

Memory analysis diagram:


2.5. Method overload: overload

Concept: multiple embodiments of a functional method in a class (with different method bodies).
give an example:
    1,Human beings have the function of eating: eat()
            eat(food);
            eat(drug);
            eat(Chewing gum);
        
    2,Summation function:
            getSum(int i,int j);
            getSum(double d1, double d2);
    3,Water:
        Normal temperature: liquid
        0 Below: solid state
        100 Above: gaseous
        
It is the method of the same function. Because of different parameters, the specific methods called are also different.
How to determine whether multiple methods are overloaded? The following three criteria shall be met at the same time:
    A: Must be in the same class.
    B: Method names must be consistent.
    C: The parameter list must be different. (order, number, type)
    
        and static,public,Return value, void It doesn't matter.
advantage:
    1,Simplified development pressure
    2,Simplified the pressure of memory
    3,The calling method is more convenient and concise, and meets different situations
        
Basic principle:
    When the method names are consistent, select the method to be executed through different formal parameter lists.

Example code:

package com.qf.demo01.overload;
​
import java.util.Arrays;
​
/*
 * Method overload:
 * Same function:
 *  According to different parameters, the specific methods of execution are also different
 * 
 * Whether the measurement method is overloaded:
 *  1,In the same class
 *  2,Method names must be consistent
 *  3,The parameter list must be different: type, number and order
 */
public class Test1 {
  //Sum two numbers:
  
  //Find the sum of two integers
  public static void getSum(int i,int j){
    int sum = i + j;
    System.out.println(i+" + " + j +"The sum of:"+sum);
  }
  
  public static void getSum(double d1, double d2){
    double sum = d1 + d2;
    System.out.println("The sum is:"+sum);
  }
  
  
  public static void getSum(int i,double j){
    
  }
  
  public static void getSum(double d1,int i1){
    
  }
​
  public static void main(String[] args) {
    getSum(1, 2);
    
    getSum(3.14, 4.21);
​
    
  }
  
  
}
​


2.6 construction method

Construction method: it is a very special method.

  • Declared syntax: public class name () {}
    • Modifier: only modifier with access permission, public. static cannot be added.
    • Return value: you cannot write void without a return value.
    • Method name: must be the same as the class name

  • Calling method: called with the new keyword
    • The new keyword is followed by the construction method.

  • Purpose: specifically used to create objects.

Common method: a piece of code with special functions. And can be called and executed multiple times.

  • Syntax of declaration: public static void main(String[] args) {}
  • Calling method: method name (argument);
  • Functions: 1. Avoid repeated code and enhance the readability of the program. 2. Improve the maintainability of the program.

1,to write java Source code for(Show people): XXX.java
2,Compile source files(The bytecode file is executed by the machine): XXX.class
  javac command  javac XXX.java
3,JVM Execute bytecode file: XXX.class
  java command  java XXX
​
Java Decompile tool: we will now class File, decompile, you can see that it is similar to the underlying language
  javap -c -l -private XXX.class
  
  

2.6.1 default construction method provided by java compiler

Problem: when creating an object, the code: new Person();Call this Person()This method is not written in the program. Where did it come from?
​
Try to Person.class Decompile the file:


Conclusion: through the decompilation tool, some contents inconsistent with the source code are found, which is the construction method automatically added to the code by the javac compiler. Used to create objects.

The java compiler finds that there is no construction method in the code. When compiling, it will automatically add a parameterless construction method for us.

If the constructor is written in the code, the compiler will no longer help us add parameterless constructors.


2.6.2 user defined construction method

One thing to remember: if no constructor is written in a class, the compiler automatically adds a parameterless constructor. But if you write constructors, the compiler doesn't add them anymore.
Our rules for writing programs:
  No parameter structure to write
  It depends on the actual situation
  There can be multiple constructors in a class. It is also a method overload.
  
Syntax for creating objects:
  new Construction method(Possible parameters);
  
If you add a self-defined construction method:
rule of grammar:
public Class name(){
​
}
public Class name(parameter list){
  Assign the value of the parameter to the attribute.
}

How to create an object? Call the constructor of a class through the keyword new. The object is created.

Declare first and then call -- > ordinary methods. It is also suitable for constructing methods.

If a constructor is not written manually in a class, the compiler will automatically add a parameterless constructor.

Example code:

class Person{
  String name;
  int age;
    public Person(){//Parameter free construction method
        
    }
    public Person(String n,int a){//Construction method with parameters
        name = n;
        age = a;
    }
}
class Test{
    public static void main(String[] args){
        Person p1 = new Person();
        p1.name = "Li Xiaohua";
        p1.age = 18;
        
        Person p2 = new Person("Wang Ergou",18);
    }
}

Note:

1. If no constructor is written in the code. The compiler automatically adds a parameterless constructor.
2. If a constructor is written in the code. The compiler will no longer add parameterless constructors to us. Coding habit: write the structure with parameters, and then write the structure without parameters.

Compare the construction method with the common method:

2.7. this keyword

Meaning: this.

2.7.1 principle of proximity

When writing code, name member variables, parameters, local variables, etc. According to the principle of seeing the name and knowing the meaning, it is easy to have naming conflicts.
In the procedure, there is a proximity principle. Once the names conflict, it depends on which statement is close.
Cause the naming conflict between member variables and local variables in the name!!!
public Person(String name,int age){//name = "Li Xiaohua"
    name = name; //=The name s on both sides refer to parameters
    age = age;
}
Because of the naming convention, see the meaning of the name. The names of member variables and local variables are the same.
Because of the principle of proximity: construction method Person In, name and age,Will be regarded as this parameter, which is a local variable.
    
I want a way to tell the compiler:=On the left is the member variable,=On the right is the parameter.
  With the help of this This keyword is resolved.

2.7.2 usage of this I

Represents the current object.

this.Property, no this What we need is local variables. Can solve the problem of naming conflicts.
public Person(String name,int age){//name = "Li Xiaohua"
    this.name = name; //=On the left is the name attribute of this
    this.age = age;
}
use this Keyword, which clearly tells the compiler, this After this name,Is the member variable. Object. No, this What we need is parameters.
    Resolve naming conflicts between member variables and local variables.
      this The point is the member variable, No this What we need is local variables.

Example code:

package com.qf.demo03;
​
public class Person {
  //Member variable
  String name;//Attribute, member variable, person with name
  int age;
  
  public Person(){
    
  }
  
  /*
   * Proximity principle: the naming of member variables and local variables conflicts. name in the method is a parameter by default.
   */
  public Person(String name,int age){//name = "Li Xiaohua"
    this.name = name; 
    this.age = age;
  }
  
  public void eat(){
    System.out.println(name+",Eat..");
  }
  
  //this, the current object. Who calls is the current object
  //When p1 is called, this refers to p1
  //When p2 is called, his refers to p2
  
  
  //Provide a function in the class: member method
  public void showInfo(){
    System.out.println("full name:"+this.name+",Age:"+age);
  }
}
​

2.7.3 usage of this II

this() refers to the constructor of the current class.

this(parameter),The construction method of representation.
If there are multiple constructor methods in a class and there is a call relationship between them, use this()To refer to this construction method. The specific construction method refers to depends on parameters.
Note: when this()If it refers to the construction method, it must be placed on the first line.

Example code:

package com.qf.demo03;
​
public class Student {
  String name;
  int age;
  String sex;
  double score;
  
  public Student(){
    System.out.println("Parameter free construction method, Student()...");
  }
  
  
  public Student(String name,int age){//Assign values to the name and age attributes
    System.out.println("Parametric construction method.. 2 parameters..");
    this.name = name;
    this.age = age ;
  }
  
  public Student(String name,int age,String sex,double score){
    this(name,age);//this() refers to the construction method.
    System.out.println("Parametric construction method.. 4 parameters..");
//    this.name = name;
//    this.age = age;
    this.sex = sex;
    this.score = score;
  }
  
  public void showInfo(){
    System.out.println("full name:"+name+",Age:"+age+",Gender:"+sex+",Achievement:"+score);
  }
}
​

2.8 anonymous objects

Syntax for creating objects:
    Person p1 = new Person();
    //=On the left is the object declaration, which opens up stack memory
    //=On the right is the real creation object
    //Result: in memory, an object is created, and the address of the object is assigned to p1.
Anonymous objects, that is, only=Right, No=left.
    new Construction method(Necessary parameters);
Purpose of anonymous object:
    1,Use anonymous objects to directly call the methods of the class.
    2,Anonymous objects are used directly as parameters to a method.
    
Note:
    Anonymous objects can only be used once. Use once as it is created. (disposable)
Advantages:
    1,It is destroyed after use GC Recycling.
    2,Code writing method to improve efficiency.

Example code:

package com.qf.demo01;
​
public class Test1 {
​
  public static void main(String[] args) {
    //Create normal objects with references and objects
    Person p1 = new Person();
    
    //Command objects through p1: you can access properties, assign values, and call methods
    p1.name = "Wang Ergou";
    p1.age = 19;
    System.out.println(p1.name);
    System.out.println(p1.age);
    
    p1.eat();
    p1.eat();
    
    
    
    //Create an anonymous object. There is no stack reference, only the objects in the heap.
    //Limitations: it can only be used once. It can be used once when creating.
    new Person().eat();
    new Person("Li Xiaohua",18).eat();
    
    
    //Only = left
    Person p2 = null;//Only object declarations
    p2.eat();
    
  }
​
}
​

Welfare at the end of the article
You can add teachers vx to get the latest information

  Don't forget to scan the code and get the [Java HD roadmap] and [full set of learning videos and supporting materials]

Keywords: JavaEE

Added by benjaminj88 on Mon, 01 Nov 2021 11:07:36 +0200