Simply put, object orientation in JAVA applies primarily to classes.

In Java, classes mainly include the following concepts: constants, variables, constructors, ordinary methods, destructors, first briefly introduce the basics, then look at a Demo code, see how you understand Java classes

  • The Java keyword final is used in front of a variable to indicate that the value of the variable cannot be changed, which is called a constant.
  • Static variables are shared in memory, unlike instance variables;
  • Static code blocks run when the class is loaded;
  • Any Java class can override the Protected Finalize () method provided by the Object class as a destructor, which, as opposed to the constructor, is executed automatically when the Object is destroyed.
package com.company.ronghui.shi;

public class Counter {

    private static int number = 0;

    Counter() {
        init();
        number++;
    }

    static {
        number++;
    }

    private void init() {
        number++;
    }

    public int getCount() {
        return number;
    }

    protected void finalize() {
        number--;
        System.out.println("Final number: "+ number); }}Copy the code
package com.company.ronghui.shi;

import java.lang.String;

public class Main{

    public static void main(String args[]) {
        run();
        Runtime.getRuntime().gc();
    }

    private static void run() {
        for (int i = 1; i <= 3; i++) {
            System.out.println((newCounter()).getCount()); }}Copy the code

The correct answer

3
5
7
Final number: 6
Final number: 5
Final number: 4
Copy the code