Java from entry to proficiency - classes and objects (2)

0. Classes and Objects

![Insert image description here](https://img-blog.csdnimg.cn/9ab78dc17d214f0f831be8f7c9defd6e.png

3. Class construction method

Insert image description here
A constructor is a special method used to create and initialize objects. The name of the constructor must be the same as the class name, it has no return value, and is automatically called when the object is created. The main role of the constructor is to ensure that the object has a suitable initial state when it is created.

The following are the basic concepts and usage of constructor methods:

3.1 Characteristics of construction methods:

  1. The name of the constructor must be the same as the class name.
  2. The constructor has no return value and does not even require the use of voidkeywords.
  3. The constructor is automatically called when the object is created and cannot be called manually.
  4. A class can have multiple constructors, overloaded with different parameter lists.
  5. If no constructor is defined for the class, Java will automatically generate a default no-argument constructor.

3.2 The role of the construction method:

The main function of the constructor is to initialize the object, and is usually used to perform the following operations:

  • Initialize the object's properties.
  • Allocate memory space.
  • Perform the necessary setup and preparation.

3.3 Construction method example:

public class Student {
    private String name;
    private int age;

    // 无参构造方法
    public Student() {
        // 默认构造方法,不执行特定初始化操作
    }

    // 带参数的构造方法
    public Student(String name, int age) {
        this.name = name;
        this.age = age;
    }

    // 其他构造方法...
}

A class is defined Studentwith two constructors: a parameterless constructor and a parameterized constructor. The constructor with parameters is used to initialize the student's name and age properties.

3.4 Use of construction methods:

public class Main {
    public static void main(String[] args) {
        // 使用无参构造方法创建对象
        Student student1 = new Student();
        
        // 使用带参数的构造方法创建对象
        Student student2 = new Student("Alice", 20);
    }
}

We create two Studentobjects using constructors, one using a parameterless constructor and the other using a parameterized constructor to initialize properties.

4. Static variables and static methods

Insert image description here
Static variables and static methods are associated with classes rather than objects. They belong to classes rather than objects, so they can be accessed directly through the class name without creating an instance of the class. Let’s dive into the concept and usage of static variables and static methods.

4.1 Static variables (static fields)

Static variables, also known as static fields or class variables, are variables declared at the class level whose values ​​are shared by all instances of the class. Static variables are usually staticmodified with keywords. The following are the characteristics and usage of static variables:

  • Static variables belong to the class and not to any instance of the class.
  • All instances of a class share the same static variables.
  • Static variables are initialized when the class is loaded and will only be initialized once.
  • Static variables can be accessed directly through the class name without creating an object.

Example:

public class Counter {
    // 静态变量
    public static int count = 0;
    
    // 静态方法
    public static void increment() {
        count++;
    }
}

In the example, Counterthe class has a static variable countthat keeps track of the count, and a static method increment()that increments the count.

4.2 Static methods

Static methods are methods declared at the class level that can be called directly without relying on an instance of the class. Static methods are usually staticdecorated with keywords. The following are the characteristics and usage of static methods:

  • Static methods belong to the class and not to any instance of the class.
  • Static methods can be called directly through the class name without creating an object.
  • Static methods cannot access non-static variables and non-static methods because they do not depend on the state of the object.

Example:

public class MathUtils {
    // 静态方法:计算两个整数的和
    public static int add(int a, int b) {
        return a + b;
    }
}

In the example, MathUtilsthe class has a static method add()that calculates the sum of two integers. This method can be called directly via the class name, MathUtils.add(5, 3)e.g.

4.3 Purpose of static variables and static methods

Static variables and static methods are typically used in the following situations:

  1. Shared data : Static variables can be used to store class-level shared data, such as counters, configuration information, etc.

  2. Utility methods : Static methods are typically used to implement class-related utility methods that can be used without creating an object.

  3. Factory Method : Static methods can be used to create instances of a class, such as static factory methods in singleton pattern.

  4. Constants : Static variables can be used to define constants, such as Math.PIrepresenting pi.

  5. Static Class : Sometimes, a static class can be created in which all methods and variables are static and used to implement utility classes or global configuration classes.

5. Main method of class

Insert image description here
In Java, the main method of a class is a special method that is the entry point of a Java program. Every Java application must contain a main method, which has the following characteristics:

  1. The declaration of the main method must look like this:

    public static void main(String[] args)
    
  2. The name of the main method must be main.

  3. The main method's argument list must include an Stringarray argument, usually named args, for receiving command line arguments.

  4. The return type of the main method is void, meaning it does not return any value.

The main function of the main method is to serve as the entry point of the program. When the program starts, the Java Virtual Machine (JVM) will call the main method to execute the logic of the program. Inside the main method, you can write the main logic of the program, process input, perform calculations, call other methods, etc.

The following is the main method contained in a typical Java program:

public class MyProgram {
    public static void main(String[] args) {
        // 主方法的逻辑代码
        System.out.println("Hello, World!");
    }
}

In the example, MyProgramthe class contains a mainmain method called , which simply prints "Hello, World!"

The main method is the entry point of a Java program, which allows you to execute the program and interact with the user or other systems. In practical applications, the main method usually contains more complex logic to achieve specific functions or tasks. When you run a Java program, the JVM finds and executes the code inside the main method.

6. Object

Insert image description here
In Java, objects are one of the core concepts of object-oriented programming. An object represents a real-world entity or concept and has properties (member variables) and methods (member methods) to describe its characteristics and behavior. Let’s dive into the concept and usage of objects.

6.1 Basic concepts of objects

  • Objects are instances of classes : classes are templates for objects, and objects are actual instances created from the template. Objects are concrete entities of a class.

  • Objects have state and behavior : the state of the object is represented by member variables (properties), and the behavior of the object is represented by member methods. State describes the characteristics of an object, and behavior describes the actions an object can perform.

  • Objects are reference types : In Java, a variable can hold a reference to an object rather than the object itself. A reference is a pointer to the memory address of an object.

In Java, object creation usually follows these steps:

  1. Define a class : First, you need to define a class that describes the properties and methods of an object.

  2. Instantiate objects : Use newkeywords to create instances (objects) of a class and allocate memory space. For example:

    ClassName objectName = new ClassName();
    
  3. Accessing objects : Through object references, you can access the properties and methods of the object. For example:

    objectName.propertyName = value; // 设置属性值
    objectName.methodName();        // 调用方法
    

6.3 Creating and using objects

public class Student {
    // 成员变量
    private String name;
    private int age;

    // 构造方法
    public Student(String name, int age) {
        this.name = name;
        this.age = age;
    }

    // 成员方法
    public void displayInfo() {
        System.out.println("姓名: " + name);
        System.out.println("年龄: " + age);
    }
}

public class Main {
    public static void main(String[] args) {
        // 创建Student对象
        Student student1 = new Student("Alice", 20);
        Student student2 = new Student("Bob", 22);

        // 访问对象的成员方法
        student1.displayInfo();
        student2.displayInfo();
    }
}

In the example, a Studentclass is defined, which has two member variables nameand agea member method displayInfo()for displaying student information. Then, in the methods Mainof the class main, we created two Studentobjects and called displayInfo()methods using the references of the objects to display the student information.

6.4 Object references and life cycle

A reference to an object is a pointer to the object's memory. References to objects can be assigned to variables, passed to methods, stored in data structures, etc. The life cycle of an object begins when it is created (instantiated) and ends when it is no longer referenced. Once an object is no longer referenced, it becomes unreachable and the memory is eventually reclaimed by the garbage collector.

Guess you like

Origin blog.csdn.net/m0_53918860/article/details/132790881