[object oriented] construction method, main method explanation, static keyword, tool class creation and help document, and create object initialization process

Posted by liamjw on Sun, 16 Jan 2022 14:17:05 +0100

object-oriented

I Construction method

1. Question: we have never written a constructor in the class before, but we can still create objects. Where is the constructor used?

    be careful:
 1,If we don't give a construction method, JVM Automatically provides a construction of an empty method body without parameters
 method
 2,If we give a construction method, will we provide it?
If we provide a construction method, the system will no longer provide the construction of the default parameterless null method body
 method
 3,Construction methods can be overloaded
 How to assign values to member variables:
 1,use setXxx(...)Assign values to private member variables
 2,Use the construction method with parameters to assign values to private member variables. Here, you need to this keyword
 Use together

3. Construction method and usage

Construction method: initializes member variables

  • Construction methods can be overloaded

  • If we do not provide a constructor, the system will provide a constructor without parameter null method body by default

  • If we provide a construction method, the system will not provide it no matter whether it provides no parameters or parameters

  • Format: the method name is consistent with the class name. There is no return value type, not even return.
    The constructor is called when the object is created.

2. Examples:

   class Construction1{
    private String name;
    private int age;

    Construction1(){
        System.out.println("This is our own parameter free construction method");
    }

    Construction1(String name){
        System.out.println("This is the tape parameter we provide name Construction method of");
        this.name = name;
    }

    Construction1(int age){
        System.out.println("This is the tape parameter we provide age Construction method of");
        this.age = age;
    }

    Construction1(String name,int age){
        System.out.println("This is what we provide with two parameters name,age Construction method of");
        this.name = name;
        this.age = age;
    }

    public void show(){
        System.out.println(name+"---"+age);
    }
}
public class ConstructionDemo1 {
    public static void main(String[] args) {
//        Construction1 construction1 = new Construction1();
//        construction1.show();

        //Use the construction method with parameters to create objects
//        Construction1 c2 = new Construction1("Zhou Jiaxiang");
//        c2.show();

//        Construction1 c3 = new Construction1(18);
//        c3.show();

        //Use the constructor with two parameters name,age to create the object
        Construction1 c4 = new Construction1("Yao long", 18);
        c4.show();
    }
}

3. Give an example of parameter requirements in the construction method/*

Define a rectangular class, define the method of calculating perimeter and area, and then define Test2 to test. Note that the length should be greater than the width

  class Rectangle {
    //Since both length and width are used to describe a rectangle, they are related to the class and are the properties of the class
    //So it is defined as a member variable
    private int length;
    private int width;

    public Rectangle() {
    }

    public Rectangle(int length, int width) {
//        this.length = length;
//        this.width = width;
        if (length >= width) {
            this.length = length;
            this.width = width;
        } else {
            System.out.println("The input data is incorrect. Please check whether the length and width meet the standard");
        }
    }

    public int getLength() {
        return length;
    }

    public void setLength(int length) {
        this.length = length;
    }

    public int getWidth() {
        return width;
    }

    public void setWidth(int width) {
        this.width = width;

    }

    //Define the method of calculating the perimeter of a rectangle
    public int getGirth() {
        return 2 * (length + width);
    }

    //Define the method of calculating the area of a rectangle
    public int getArea() {
        return length * width;
    }

    public void show() {
        System.out.println("Length:" + length + "Width:" + width);
    }


}

public class Test2 {
    public static void main(String[] args) {

        Rectangle rectangle = new Rectangle(5, 10);

        int girth = rectangle.getGirth();
        System.out.println("Perimeter:" + girth);
        int area = rectangle.getArea();
        System.out.println("Area:" + area);
    }
}

Note: if you do not provide a construction method, the system will automatically provide a construction method without parameter null method body. When in the inheritance relationship, when the child class is initialized, the parent class must be initialized first, and the construction method of the parent class must be executed first.

II main method explanation

Format explanation of main method:
public static void main(String[] args){...}

public: Public, access is maximum because main By JVM Called, so permissions
 Big enough
static: It is static and does not need to create objects. It is convenient to call directly through the class name JVM visit
void: It means no return value, because we directly said that the return value is returned to the caller, and the caller
 use main The method is by JVM It is meaningless to call and return to him
String[] args: The parameter is a string array. The array parameter is named args?
 How does this thing work? What if you pass it on? Where is it worth going?
 early stage JDK1.5 Before, No Scanner When typing, how did the programmer give the program at that time
 What about sequence parameters? It's here args Transmission parameter
        How?
          1,IDEA Parameters can be passed directly
          2,Command parameters
          java MainDemo hello world java

give an example:

 public class MainDemo {
    public static void main(String[] args) {
        for(int i=0;i<args.length;i++){
            System.out.println(args[i]);
        }
    }
}

III static keyword

1. Introduction

Define a person's class
After we defined and used it, we found that the name and age are different and change. We can understand that because everyone's name and age are different.
However, up to now, the people we have chosen are all Chinese. Their nationalities are the same. They are all Chinese.
For the same nationality, we will open up such a member variable space in the heap memory every time we create it.
When there are many people of the same nationality, this will cause a waste of memory. What should we do?
When multiple objects have common member variables and the values are the same.
java provides us with a keyword called static

Static: static
It can modify member variables and member methods. Its function is to make all objects share a member variable

2. Features

static keyword features: it can modify member variables and member methods

  • Loads as the class loads
    Observe the main method

  • Existing prior to the object and does not change with the change of the object.

  • Shared by all objects of the class:
    For example: the nationality information of all Chinese is the same as that of China.
    When to use the static keyword?
    If a member variable is shared by all objects and has the same value, it should be defined as static.
    Examples of real life cases:
    Harrow shared bike (can be decorated with static)
    Own water cup (static decoration is not allowed)

  • It can be called directly through the class name
    Generally, as long as we see a member variable or member method with static modification in a class
    We always recommend using class names Static members are used in this way
    The content of static modification is generally called class member, which is related to class.
    give an example:

class Student2{
    //Non static member variables
    int num = 20;

    //Static member variables
    static int num2 = 30;
}

public class StaticDemo1 {
    public static void main(String[] args) {
        Student2 s1 = new Student2();
        System.out.println(s1.num);
//        System.out.println(s1.num2);
        System.out.println(Student2.num2);
    }
}

3. Precautions

Precautions for using static keyword:
1. There is no this keyword in static methods
this represents the object that currently calls the method, and the member modified by static is preceded by an object.
The static modified member is loaded with the loading of the class. At this time, no object has been generated, which means that there is no this keyword
Therefore, the this keyword cannot be used in static methods.
2. Member methods are divided into two categories:
Static member method:
Content accessed:
Member variables: only static member variables can be accessed
Member methods: only static member methods can be accessed
Non static member method:
Content accessed:
Member variables: you can access both non static and static member variables
Member methods: you can access both non static and static member methods

If you really can't remember this, sum up: static can only access static.
give an example:

  class Student3 {
    private String name;
    private int age;
    private static int a;

    public Student3() {
    }

    public Student3(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;
    }

//    public static int getAgeAgain(){
//        return this.age;
//    }
    public static void fun1(){
        //An attempt was made to access a non static member variable name
        //Non static variable name cannot be referenced from a static context
        //Static member methods cannot access non static member variables
//        System.out.println(name);

        //Trying to access a static member variable a
        //Static member methods can access static member variables
        System.out.println(a);

        //Attempt to access non static member method show()
        //Non static method show() cannot be referenced from a static context
        //Static member methods cannot access non static member methods
//        show();

        //Try a static member method function()
        //Static member methods can access static member methods
        function();

    }

    public void fun2(){
        //An attempt was made to access a non static member variable name
        //Non static member variables can access non static member methods
        System.out.println(name);

        //Trying to access a static member variable a
        //Non static member methods can access static member variables
        System.out.println(a);

        //Attempt to access non static member method show()
        //A non static member method can be a non static member method
        show();

        //Try a static member method function()
        //Non static member methods can access static member methods
        function();

    }

    public static void function(){

    }

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

public class StaticDemo2 {
    public static void main(String[] args) {

    }
}

4.static memory allocation diagram


IV Tool class creation and help documentation

1. Notes for tool class creation:

  • The construction method is privatized and cannot be created or changed by the outside world.

  • The methods in the tool class are statically decorated so that the outside world can access them directly through the class name

2. How to make instructions (help documents)

1. Tool class
2. Generate help documents with document comments
How to add notes? Look at ArrayTool
What can I add? Look at ArrayTool
How?
Format: javadoc -d Directory - Author - version arraytool java
-d directory of output help documents
Note: we need to create v manually

3. Examples

  • The first is an array class ArrayDemo
public class ArrayDemo {
    public static void main(String[] args) {
        int[] arr = {21,32,55,11,2,10};
        //Static methods can only be static member methods
//        printArray(arr);
        //Traverse the array by using the utility class
        ArrayTool.printArray(arr);
        //Tools are not allowed to be changed by the outside world
        //You cannot create objects from outside
        //How to prevent the outside world from using tool classes to create objects?
//        ArrayTool arrayTool = new ArrayTool();
        //Privatize construction methods
  • Creating a tool class ArrayTool
/**
 * This is a tool class for array related operations
 * @author Little tiger
 * @version V.1.0
 *
 */
public class ArrayTool {
    /**
     * This is a private parameterless construction method
     */
    private ArrayTool(){

    }


    /**
     * This is the method of traversing the array. The format after traversal is [element 1, element 2, element 3...]
     * @param array This is the parameter that needs to be passed in when calling this method. The data type is an array of int type
     */
    public static void printArray(int[] array){
        for(int i=0;i<array.length;i++){
            if(i==array.length-1){
                System.out.print(array[i]+"]");
            }else if(i==0){
                System.out.print("["+array[i]+",");
            }else {
                System.out.print(array[i]+",");
            }
        }
        System.out.println();
    }

    /**
     * This is the reverse order of the array
     * @param array This is the parameter that needs to be passed in when calling this method. The data type passed in is an array of int type
     * @return Returns an array in reverse order
     */
    public static int[] niXu(int[] array){
        for(int start=0,end=array.length-1;start<=end;start++,end--){
            int temp = array[start];
            array[start] = array[end];
            array[end] = temp;
        }
        return array;
    }
}

V Create object initialization process

a:First class The file is loaded into the method area
b:Make room for variables in the stack
c:Create objects in heap memory
d:The system assigns default values to member variables
e:***Assign display values to member variables***
f:***Constructors assign values to member variables***
g:Assign an address in heap memory to a variable in stack memory

Topics: Java Back-end OOP