Make writing a habit together! This is the fourth day of my participation in the “Gold Digging Day New Plan · April More text Challenge”. Click here for more details.


⭐️ ⭐️

This article introduces you to Java classes and objects. I’m sure you’ve all heard of object-oriented programming. Java is an object-oriented programming language, unlike C, which is a procedural programming language. The difference between object orientation and process orientation can be understood as object orientation, object refers to a thing, nominal, process orientation, process refers to doing something, dynamic, for example, you want to put an item in the refrigerator, process orientation is to open the refrigerator door -> put in the refrigerator -> close the refrigerator; Object oriented is object -> refrigerator. Classes and objects themselves are very abstract concepts that require more understanding and practice. The following text will introduce you to classes and objects in Java.

📒 blog homepage: not seen flower smell blog homepage 🎉 welcome to pay attention to 🔎 like 👍 collect 🎉 🎉 message 📒 📆 Nuggets debut: 🌴 April 5, 2022 🌴 ✉️ Perseverance and hard work will be exchanged for poetry and distance! 💭 refer to books: 📚 “Java programming ideas”, 📚 “Java core technology” 💬 refer to online programming website: 📚 niuke.com SILVER force to deduct the code cloud of the blogger gitee, usually the program code written by the blogger are in it. Github of the blogger, the program code written by the ordinary blogger is in it. 🍭 author level is very limited, if you find mistakes, be sure to inform the author in time! Thank you, thank you!


🔮1. Introduction to classes and objects

A class is a template or blueprint for constructing an object. We can think of classes as cookie cutters and objects as cookies. The process of constructing an object from a class is called creating an instance of the class.

Instantiate a class. The instantiated class is an object.

C language is process-oriented, focusing on the process, analyzing the steps to solve the problem, and solving the problem step by step through function calls. JAVA is object-oriented and focuses on objects, breaking one thing into different objects and relying on the interaction between objects. Process-oriented focuses on the process, and the behavior involved in the whole process is function. Object orientation focuses on objects, the subjects involved in the process. It is the logic that connects one functional implementation to another.

Process-oriented: 1. open the refrigerator 2. put the elephant in 3. close the refrigerator

Object oriented: open refrigerator, store, close are the operation of refrigerator, is the behavior of refrigerator. The refrigerator is an object, so as long as the operation of the refrigerator has the function, must be defined in the refrigerator.

The concept of classes and objects is very abstract. The following is an introduction to the application of classes and objects.

🔮2. Classes and instantiation of classes

🎃2.1 Class creation

🎁 Customize the format of a class:

class ClassName {
    // Members: 1. Variables (fields/attributes) 2. Methods
}
Copy the code

(1) The class name is named in the big hump form

(2) There can be only one public class in a. Java file

(3) Members of a class can be variables (fields/attributes), methods, static variables, and static methods.

Such as:

class Student {
    public String name;
    public String sex;
    public int age;
    public String id;
        
    public void setName(String str){ name = str; }}Copy the code

Instantiation of the 🎃2.2 class

The class defined by us can be understood as an architectural drawing (blueprint). The process of building a house according to the content of this drawing is called instantiation of the class, and the instantiated “house” is the object.

Of course, a single design drawing can instantiate multiple buildings, all of which have the same properties. In other words, a class can instantiate multiple objects.

In Java, the class is instantiated with the new keyword, which I’m sure you’re familiar with, because we used the new keyword in the previous input and array definition.


Class name Variable name =   n e w The name of the class ( Constructor argument ) ; Class name variable name = new class name (constructor argument);

The constructor argument, let’s ignore it, can be omitted.

For example, we define a class like this:

class Student {
    public String name;
    public String sex;
    public int age;
    public String id;
    public String major;
    
    public void getName(a) {
        System.out.println(name);
    }
    public void getMajor(a) { System.out.println(major); }}Copy the code

The instantiation of this class is as follows:

public class ClassCreat {
    public static void main(String[] args) {
        Student stu = new Student();// instantiate the object
        stu.name = "weijianhuawen";// access the instantiated object stu using
        stu.sex = "man";
        stu.major = "computer";
        stu.getMajor();// Use the same method to access the objectstu.getName(); }}Copy the code

Use the variable stu defined by the Student class as the reference variable, whose value is the address of the instantiated object.

🔮3. Members of the class

🎃3.1 Member variables

Variables defined outside a method in a class are called member variables of a class. Member variables are also called fields or attributes.

class Variable {
    public int a
    public double pi;
    public String str;
}
Copy the code

Variables defined outside of a method in a class like this are member variables. If we need to use this class, we need to instantiate an object with new before we can access its members. By instantiating multiple objects from a class, each object is independent. Modifying the value of one object does not change the value of the other object. Finally, a member variable in a class may or may not initialize its own value. This is different from local variables defined in a method, but it generally does not initialize its own value. If a member variable is not initialized, it will have a default value.

public class ClassCreat {
    public static void main(String[] args) {
        Variable var = new Variable();
        System.out.println(var.a);
        System.out.println(var.pi);
        System.out.println(var.str);
        var.pi = 3.14;
        var.a = 12;
        System.out.println(var.a);
        System.out.println(var.pi);
        System.out.println("-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -");
        Variable var2 = newVariable(); System.out.println(var2.a); System.out.println(var2.pi); }}Copy the code

🎃 3.2 method

A class can define methods in addition to member variables. For example, the main method is defined in a class.

class Menthod {
    public double a;
    public double b;

    public double add(double x, double y) {
        return x + y;
    }
    public double sub(double x, double y) {
        returnx - y; }}Copy the code

We define a class with two member variables and member methods. If we want to use this class, we need to instantiate it as an object before we can access the variables or methods in the object.

public class ClassCreat {
    public static void main(String[] args) {
        Menthod men = new Menthod();
        men.a = 3.14;
        men.b = 2.88;

        double sum = men.add(men.a, men.b);
        double sub = men.sub(men.a, men.b);

        System.out.printf("The sum is %.2f\n and the difference is %.2f\n", sum, sub); }}Copy the code

🎃3.3 Static variables and static methods

The member variables and methods we defined above outside of the methods in the class belong to objects and are stored in the heap. Static variables or methods are stored in the method area, and classes are also stored in the method area, so static variables or methods are also called class variables and class methods. Static variables and static methods belong to classes, so they don’t need to be instantiated to use them. Of course, since they belong to classes, if you change the value of a static variable in one object, the value of the static variable will be the changed value when you access it in another object.

class StaticMember {
    public static int x;

    public static int add(int a, int b) {
        returna + b; }}Copy the code

The class defined above has a member variable, b a static member variable, and a static method add. Using static variables or methods does not require class instantiation (of course you can instantiate an object and then access it from the object, which is fine), a must instantiate the object.

public class ClassCreat {
    public static void main(String[] args) {
        int a = 12;
        int sum = StaticMember.add(a, StaticMember.x);
        System.out.println(sum);
        System.out.println("-- -- -- -- -- -- -- -- -- -- -- --");
        StaticMember sm1 = new StaticMember();
        sm1.x = 14;
        sum = sm1.add(a, sm1.x);
        System.out.println(sum);
        System.out.println("-- -- -- -- -- -- -- -- -- -- -- --");
        StaticMember sm2 = newStaticMember(); sum = sm2.add(a, sm2.x); System.out.println(sum); }}Copy the code

🔮4. Class encapsulation

🎃4.1 Privite implementation encapsulation

We defined in the class variables or methods, above all is to use the public keyword modifiers, using the key words of a variable or method, according to the variable or method is public, can be used in the middle of the other and the current class, but if you use the privite keyword modify variables or methods, according to the variable or method is private, Only the class it belongs to can access and use, in other classes cannot access or call this variable or method, which also reflects the Security of Java.

Take a look at the following code:

class PriviteMember {
    private int add(int a, int b) {
        returna + b; }}public class ClassCreat {
    public static void main(String[] args) {
        PriviteMember pm = new PriviteMember();
        int x = 10;
        int y = 12; System.out.println(pm.add(x, y)); }}Copy the code

Since we made the Add method private in the PriviteMember class, and then instantiated the object in another class and used Add, we found that the compiler reported an error!

If the calladd(in the example programmianMethod) andaddIn the same class, execute the program again:

public class ClassCreat {
    private int add(int a, int b) {
        return  a + b;
    }
    public static void main(String[] args) {
        ClassCreat pm = new ClassCreat();
        int x = 10;
        int y = 12; System.out.println(pm.add(x, y)); }}Copy the code

We found that this method works:

🎃4.2 Getter and setter methods

A variable or method modified by the keyword privite can only be used in the same class. What if we wanted to change or call that variable or method in another class? This is possible, but indirectly-we define a public method in the class of the privite variable or method to access and modify the privite member.

We can write a class like this:

class PriviteMember {
    private int m;
    private double n;
    private int add(int a, int b) {
        return  a + b;
    }
    
    public int getterInt(a) {
        return m;   //获取m
    }
    public double getterDouble(a) {
        return  n;//获取n
    }
    public void setterInt(int x) {
        m = x;/ / set m
    }
    public void setterDouble(double y) {
        n = y;/ / set n
    }
    public int getAdd(int x, int y) {
        return add(x, y);// Call the private method add}}Copy the code

We can indirectly access and modify private members by calling other public variables or methods in other classes.

public class ClassCreat {
    public static void main(String[] args) {
        PriviteMember pm = new PriviteMember();
        pm.setterInt(12);// Assign to m
        System.out.println(pm.getterInt());// get the value of m
        
        pm.setterDouble(3.14);// Assign to n
        System.out.println(pm.getterDouble());// Get the value of n

        int a = 14;
        int b = 12;
        System.out.println(pm.getAdd(a, b));// Call the private method add indirectly}}Copy the code

In the idea compiler, getters and setters are automatically generated to set and get the values of private variables in a class or the return values of private methods.

In the IDEA compiler, right-click Generate in the code area, click Generate, and select Getter or Setter to automatically help you Generate Settings and get values for private member variables.

Select a Getter or Setter as needed, and then select the variable you want to access, holding CTRL to make multiple selections.

The this keyword modifier represents a reference in the current object that can be used to access member variables and methods of the current object.

🔮5. Construction method

🎃5.1new Execution process

👻5.1.1new Object instantiation process

Instantiating an object with the keyword new is a two-step process:

  1. Allocates memory space for objects
  2. Call the constructor (if there are no constructors in the class, a constructor with no arguments is automatically generated)

👻5.1.2 Construction method

A constructor is a special method that is automatically called when a new object is instantiated using the keyword new, so the constructor is defined in a class. It has the following characteristics:

  1. Method names must be the same as class names.
  2. No return value.
  3. There is at least one constructor in each class, and if none is defined in the class, a constructor with no arguments is automatically generated.
  4. Constructors support overloading, the same rules as normal method overloading.
  5. If a constructor with arguments is defined in a class, the default no-argument constructor is no longer generated.

🎃 5.2 this keyword

When setters are used to generate functions, variables in automatically generated functions are modified by this, which refers to references in the current object and can be used to access member variables and methods of the current object.

❗ ️ attention! This said the current object reference, not the current object, in the constructor we can use this, but when to invoke a constructor, the object also didn’t finish, instantiation is allocated memory, that object is not defined, but the references have been generated, because of the memory allocation completed, then the address also came out, The quotes came naturally. So this represents a reference to the current object, not the current object.

The keyword this can be used in three ways:

way explain
This. Member variable name Accessing properties (member variables) of the current object
This. Method name (corresponding argument list) Calls a method of the current object
this() Calling other constructors of the current object in a constructor must be on the first line of the constructor

The following code proves that this can be used in a constructor:

class ConstructionMethod {
    public int a;
    private int b;

    public ConstructionMethod(a) {
        System.out.println("This is a no-argument constructor!");
    }
    public ConstructionMethod(int x) {
        this.b = x;
        System.out.println("This is a constructor with arguments! Member variable b can be assigned! B =" + this.b);
    }
    public ConstructionMethod(int x, int y) {
        this.a = this.add(x, y);
        System.out.println("This is a constructor with two arguments! You can calculate the sum of two integers! The sum of these two numbers is: + a);
    }
    private int add(int m, int n) {
        returnm + n; }}Copy the code
public class ClassCreat {
    public static void main(String[] args) {
        ConstructionMethod cm1 = new ConstructionMethod();
        System.out.println("-- -- -- -- -- -- -- -- -- -- -- --");
        ConstructionMethod cm2 = new ConstructionMethod(12);
        System.out.println("-- -- -- -- -- -- -- -- -- -- -- --");
        ConstructionMethod cm3 = new ConstructionMethod(18.2); }}Copy the code

🔮 6. Code block

🎃6.1 Common code block

A normal code block is a code block defined in curly braces within a method, for example:

public class ClassCreat {
    public static void main(String[] args) {{int a = 12;
            int b = 48;
            String name = "weijianhuawen"; }}}Copy the code

🎃6.2 Construct code blocks

Constructor blocks are code blocks defined outside a method in a class, also called instance blocks. They are commonly used to initialize member variables (I feel redundant), for example:

class CodeBlock {
    private int c;
    private int d;
    public int sum;

    // Construct a code block or instance code block
    {
        this.c = 10;
        this.d = 12;
        sum = this.add(c, d);
    }
    
    public int add(int x, int y) {
        returnx + y; }}Copy the code

❗️ Note: Constructor (instance) code blocks take precedence over constructor execution.

🎃6.3 Static code blocks

Construction blocks that use static modifiers are called static blocks, and are typically used to initialize properties of static member variables. It is stored with the class, in the method area.

class CodeBlock {
    public static int a;
    public static String name;
    
    // Static code block
    static {
        a = 18;
        name = "No flowers in sight."; }}Copy the code

❗ ️ note:

  1. A static code block executes only once and first, no matter how many objects it generates.
  2. After the static code block completes execution, the instance code block (the constructor block) executes, followed by constructor execution.

🔮 7. Object

🎃7.1 Output object data

What do we print when we print a reference to a class? Let’s give it a try:

class Student {
    public String name;
    public String sex;
    public int age;
    public String id;
    public String major;

    public void getName(a) {
        System.out.println(name);
    }
    public void getMajor(a) { System.out.println(major); }}public class ClassCreat {
    public static void main(String[] args) {
        Student sc = new Student();
        sc.name = "weijianhuawen";
        sc.sex = "man";
        sc.age = 1;
        sc.id = "5201314";
        sc.major = "computer"; System.out.println(sc); }}Copy the code

Why is it not an address? Because Java is very secure, it handles the address and uses the toString method to return a string, which is exactly what the printed data is. For the toString method, let’s go back to the println method: Hold down CTRL and click to enter println:

By tracing, we know that printing a reference produces a string like the class name @ hash value of the reference. Let’s try writing a method that returns the same value as the toString method. Suppose I write it like this and put it in the Student class:

public String toString(a) {
    return "No flowers in sight.";
}
Copy the code

Let’s run the program again:

class Student {
    public String name;
    public String sex;
    public int age;
    public String id;
    public String major;

    public String toString(a) {
        return "No flowers in sight.";
    }
    public void getName(a) {
        System.out.println(name);
    }
    public void getMajor(a) { System.out.println(major); }}public class ClassCreat {

    public static void main(String[] args) {
        Student sc = new Student();
        sc.name = "weijianhuawen";
        sc.sex = "man";
        sc.age = 1;
        sc.id = "5201314";
        sc.major = "computer"; System.out.println(sc); }}Copy the code

Got my own written toString the returned string, this is to rewrite method, if the method and the method of the parent class subclass return value parameter and its parameters have the same number, constitutes rewriting method, will prioritise the subclass methods (the content in detail in the subsequent blog about inheritance, here to understand). Student is a subclass, and the toString method is in Object, which is the parent class, so it takes precedence over the toString method I wrote.

The IDEA compiler automatically generates the toString method, which optionally outputs the data of a class’s member variables. Similar to generating getters and setters automatically:

Automatically generated code:Let’s run the program again:

class Student {
    public String name;
    public String sex;
    public int age;
    public String id;
    public String major;

    @Override
    public String toString(a) {
        return "Student{" +
                "name='" + name + '\' ' +
                ", sex='" + sex + '\' ' +
                ", age=" + age +
                ", id='" + id + '\' ' +
                ", major='" + major + '\' ' +
                '} ';
    }

    public void getName(a) {
        System.out.println(name);
    }
    public void getMajor(a) { System.out.println(major); }}public class ClassCreat {

    public static void main(String[] args) {
        Student sc = new Student();
        sc.name = "weijianhuawen";
        sc.sex = "man";
        sc.age = 1;
        sc.id = "5201314";
        sc.major = "computer"; System.out.println(sc); }}Copy the code

🎃7.2 Anonymous Objects

An anonymous object is one that does not use a class reference variable, but is called directly. The resulting object is disposable and can only be accessed once, because you can’t find it after that.

  1. Objects without references are called anonymous objects.
  2. Anonymous objects can only be used when creating objects.
  3. If an object is only used once and no longer needs to be used, consider using anonymous objects.
class AnonymousObject {
    public int a;

    public AnonymousObject(a) {
        this.a = 188; }}public class ClassCreat {
    public static void main(String[] args) {
        System.out.println(newAnonymousObject().a); }}Copy the code