Java object-oriented basic knowledge summary

Classes and Objects Overview

1 Brief description of classes and objects

(1) Classes are abstract and are a general term, such as humans and dogs, which are general terms

(2) The object is specific, and it is a specific instance, such as a teddy dog ​​named Diandian

(3) Class is the general term for the types of objects, and objects are specific instances of the class

(4) Object attributes: used to describe the specific characteristics of the object, such as the hair color of Dian Dian, etc.

(5) Object method: used to describe the specific function of the object

2 The relationship diagram is as follows

Two member methods and member variables (properties)

1 member variable

(1) Concept

Member variable = attribute = field (that is, member variables are used to represent attributes)

A property is an integral part of a class, generally a basic data type, or a reference data type (array, object)

(2) Attribute definition syntax

public class Explain {
    public static void main(String[] args) {
        Dog dog = new Dog();//创建Dog对象
        System.out.println(dog.name);//对象引用
    }
}
class Dog{
      访问修饰符 属性类型 属性名;
      String name = "点点";
      int age = 3;
}

(3) Note

If the attribute is not assigned, it will have a default value, and different data types will have different default values, int 0, short 0, byte 0, long 0, float 0.0, double 0.0, char \u0000, boolean false, String null

2 member methods

(1) Member method syntax

Create a class named Dog


class Dog{
    成员方法的形式:
    修饰符 返回值类型 方法名(参数列表....){
           return 返回值;
    }
    public String bark(){
        return "bark";
    }
}

(2) Return value problem

  1. When there is no return value requirement, that is, the return value type is void, there may be no return statement in the method body, or only write return

  1. When there is a return value, the last statement executed in the method body must be the return value

  1. A method has at most one return value. If you want to return multiple values, you can create an array and store the values ​​in the array

  1. The return value type can be any type, including basic types or reference types (arrays, objects)

(3) Parameter list problem

  1. A method can have 0 parameters or multiple parameters, separated by commas

  1. The parameter type can be a basic data type or a reference data type

  1. When calling a method with parameters, you must pass in parameters of the same type or compatible types corresponding to the parameter list

  1. The parameters in the method definition are called formal parameters, referred to as formal parameters; the parameters in the method call are called actual parameters, referred to as actual parameters

(4) Method call details

//1 一个类中的不同方法,可以直接调用
class A{
    public void print(int n){
        System.out.println("print方法被调用" + n);
    }
    public void printAgain(){
        print(10);
    }
}
//2 跨类方法的调用,A类调用B类的方法,需要通过对象名调用
class A{
    public void a(){
        B b = new B();
        b.b();
    }
}
class B{
    public void b(){
        System.out.println("B类中的方法被调用");
    }
}

Note: Cross-class method calls are very related to method access modifiers

(5) Parameter passing mechanism of member methods

If the parameter list of the method is a basic data type, then the input of the actual parameter corresponds to the basic data type. Note that the basic data type transfers a value copy, and any change in the formal parameter (value in the parameter list) does not affect the actual parameter.

On the contrary, if it is a reference type transfer, its transfer is also a value, but the value is an address, and the actual parameter can be affected by the formal parameter

(6) Benefits of the member method

The details of the implementation can be encapsulated and then called by other users

Improved code reusability

3 How to create objects

以声明dog对象为例,类名为Dog//
//1 先声明再创建
Dog dog;
dog = new Dog();
//2 直接创建
Dog dog = new Dog();

Existence form of three objects in memory

The data area when the Java virtual machine is running can be simply divided into stack area, heap, and method area

1 stack area

The thread is private, and the life cycle is consistent with the thread. Describes the memory model of Java method execution: each method will create a stack frame (Stack Frame) to store local variable table, operand stack, dynamic link, method exit and other information when it is executed. From the call to the end of execution, each method corresponds to the process of a stack frame being pushed from the virtual machine stack to popped from the stack.

It can be known from the reference that when a Java method is executed, a new space will be created in a stack area

Local variable table: store various basic data types that exist during compilation

2 heap area

For most applications, this area is the largest piece of memory managed by the JVM. Thread sharing mainly stores object instances and arrays. Internally, multiple thread-private allocation buffers (Thread Local Allocation Buffer, TLAB) are divided. It can be located in a physically discontinuous space, but must be logically continuous.

3 method area

It belongs to the shared memory area and stores data such as class information, constants, static variables, and code compiled by the just-in-time compiler that have been loaded by the virtual machine.

Four variable scope

1 Overview

In Java programming, the main variables refer to attributes (member variables) and local variables

2 scope classification

Global variable: refers to the attribute, the scope is the entire class body, for example, the method in the Dog class can be used

Local variables: variables other than attributes, scoped to the code block in which they are defined. That is to say, local variables generally refer to variables defined in member methods

3 points to note

  1. Global variables can be used without assignment because they have default values.

  1. Local variables must be assigned a value before they can be used because they have no default value.

  1. Attributes and local variables can have the same name, and the proximity principle should be followed when accessing

  1. In the same scope, such as in the same member method, two local variables cannot have the same name

  1. The scope is different: global variables can be called by this class, or used by other classes. Local variables can only be used in the corresponding methods of this class

  1. Modifiers are different: global variables can be modified, local variables cannot be modified

Five method recursion

1 Introduction

Method recursion: recursion means that the method calls itself, passing in different variables each time it is called, and finally achieves the goal

2 codes

public class Method {
    public static void main(String[] args) {
        T t = new T();
        t.test(4);
    }
}
class T{
    public void test(int n){
        if (n > 2){
            test(n - 1);
        }
        System.out.println("n=" + n);
    }
}

3 Important rules for recursion

(1) When a method is executed, a new protected independent space (stack space) is created. For details, refer to the existence form of the object in memory

(2) The local variables of the method are independent and will not affect each other

(3) The recursion must approach the condition of exiting recursion, otherwise it is infinite recursion

(4) When a method is executed, or encounters a return, it will return, and whoever calls it will return the result to whomever it is called. At the same time, when the method is executed or returned, the method will be executed.

Six method overloading

1 Introduction

In Java, multiple methods with the same name are allowed in the same class, but the formal parameter lists are required to be inconsistent

2 Precautions

Method name: must be the same

Formal parameter list: must be different (formal parameter type or number or order, at least one is different, parameter name is not required)

Return type: None required

Seven variable parameters

1 Introduction

Java allows multiple methods with the same name and function but different numbers of parameters in the same class to be encapsulated into one method . You can achieve the expected effect by changing the number of parameters

2 Basic Grammar

access-modifier return-type method-name(data-type...parameter-name){

}

3 Precautions

  1. The actual parameters of variable parameters can be 0 or any number

  1. The actual parameter of the variadic parameter can be an array

  1. The essence of variable parameters is an array

  1. Variable parameters can be placed in the formal parameter list together with ordinary type parameters, but it must be ensured that variable parameters are placed at the end of the formal parameter list

  1. Only one variable parameter can appear in a parameter list

4 cases

//求多个数的和
public class VarParameter {
    public static void main(String[] args) {
        VarMethod varMethod = new VarMethod();
        int i = varMethod.sum(1,2,3);
        System.out.println("总和为" + i);
    }
}
class VarMethod {
    int sum = 0;
    public int sum (int... num){
        //可变参数的本质为数组,所以要访问形参num中的值,就要遍历它
        for (int i = 0; i < num.length; i++) {
            sum += num[i];
        }
        return sum;
    }
}

Eight constructors (construction methods)

1 Basic introduction

The construction method is also called the constructor (constructor), which is a special method of the class. Its main function is to complete the initialization of new objects.

2 Basic Grammar

[modifier] method name (formal parameter list) {

}

3 Precautions

  1. Constructor modifiers can default to

  1. The constructor does not return a value

  1. The constructor method name must be the same as the class name

  1. Parameter lists are as regular as parameter lists for member methods

  1. When creating an object, the system will automatically call the constructor of the class to complete the initialization of the object

4 Exercises for constructing methods

public class Constructor {
    public static void main(String[] args) {
        //通过构造器指定人的姓名和年龄
        Person person = new Person("Tom",18);
        System.out.println("person对象的名字" + person.name);
        System.out.println("person对象的年龄" + person.age);
    }
}
class Person{
    String name;
    int age;
    public Person(String pName,int pAge){
        System.out.println("构造器已被调用");
        name = pName;
        age = pAge;
    }
}

5 Precautions

  1. A class can define multiple different constructors, that is, constructor overloading

  1. The constructor is to complete the initialization of the object, not to create the object

  1. When creating an object, the system automatically calls the constructor of the class

  1. If no constructor is defined, the system will automatically generate a default no-argument constructor (also called the default constructor) for the class

  1. Once you define your own constructor, the default constructor is overwritten, and you can no longer use the default no-argument constructor

  1. The constructor is to complete the initialization of the object, and the object must have properties and methods. Therefore, before using the constructor, you must also set the corresponding properties for the object

Nine this keyword

1 What is this

The Java virtual machine assigns this to each object, representing the current object

2 the key used by this

Which object calls, this represents which object

3 Precautions and usage details

  1. The this keyword can be used to access properties, methods, and constructors of this class

  1. this can be used to distinguish properties of the current class from local variables

If the this.name in the above figure is changed to name, it will cause the property and local variable to have the same name, and it will adopt the approach of the principle of proximity to deal with it accordingly. Causes no initialization of object properties

  1. The syntax for accessing member methods: this. method name (parameter list);

  1. Access constructor syntax: this (parameter list); note that it can only be used in the constructor (that is, only another constructor can be accessed in the constructor)

For this call, the first statement in the constructor must call

public class thisDetail {
    public static void main(String[] args) {
        Person person = new Person();
    }
}
class Person{
    String name;
    int age;
    public Person(){
        this("jack",18);
        System.out.println("Person() 构造器被调用");
    }
    public Person(String name,int age){
        this.name = name;
        this.age = age;
        System.out.println(name);
        System.out.println(age);
    }
}
  1. this cannot be used outside the class definition, it can only be used in the method defined by the class (that is, it cannot be scribbled)

Guess you like

Origin blog.csdn.net/qq_67896626/article/details/128536067