Classes and objects (JAVA explanation)

1. Preliminary cognition of class and object


Before we begin to understand classes and objects in JAVA, let's take a look at the differences between C language and JAVA language:
C language is process oriented, focuses on the process, analyzes the steps to solve the problem, and gradually solves the problem through function call.
JAVA is based on object-oriented and focuses on objects. It divides one thing into different objects and completes it by the interaction between objects.
Process oriented focuses on the process, and the behavior involved in the whole process is function.
Object oriented focuses on objects, that is, the subjects involved in the process. It is to connect each function realization through logic.

1.1 object oriented concept

  1. Object oriented is a way of thinking and an idea. For example: concepts and examples, theory and practice, name and reality, etc.
  2. Class is a general term for a class of objects. An object is an instance of this kind of materialization.
  3. The benefits of object orientation: make complex things simple, just face an object.

1.2 object oriented design

Object oriented design holds an important experience: who owns data and who provides external methods to operate these data (private)! (the passive party is the owner of the data, and the active party is the executor)
In short, object-oriented is a way to use code (class) to describe things in the objective world. A class mainly contains the attributes and behavior of a thing.

2. Classes and instantiation of classes

2.1 what are classes?

Class is a general term for a class of objects. An object is an instance of this kind of materialization.

Simple example: the model we use to make moon cakes is a class, and we can make moon cakes through this model. In this example, the class is the model and the moon cake is the object, so the moon cake is an entity. A model can instantiate countless objects.
In general: a class is equivalent to a template, and an object is a sample generated by the template. A class can produce countless objects.
Declaring a class is to create a new data type, and the class is a reference type in Java. Java uses the keyword class to declare the class.
Basic syntax:

// Create class
class <class_name>{  
    field;//Member properties
    method;//Member method
}
// Instantiate object
<class_name> <Object name> = new <class_name>();

Class is the keyword defining the class, ClassName is the name of the class, and {} is the body of the class.
The elements in the class are called member attributes. The functions in the class are called member methods.

Code example:

class Person {
    public int age;//Member property instance variable
    public String name;
    public String sex;
    //Member method
    public void eat() {
       System.out.println("having dinner!");  
   }
    public void sleep() {
       System.out.println("sleep!");  
   }
}

Different from the method written before, the method written here does not take the static keyword. What static does will be explained in detail later.

2.2 instantiation of class

The process of creating objects with class types is called class instantiation

  1. A class is just a model that defines which members a class has.
  2. A class can instantiate multiple objects. The instantiated objects occupy the actual physical space and store class member variables.
  3. For example, instantiating an object by a class is like building a house using an architectural design drawing in reality. A class is like a design drawing. It only designs what it needs, but there is no physical building. Similarly, a class is only a design. The instantiated object can actually store data and occupy physical space.

A class can instantiate multiple objects, just like I have a design drawing, so I can build many houses of this type.

The following is a code example:

class Person {
    public int age;//Member property instance variable
    public String name;
    public String sex;
    public void eat() {//Member method
        System.out.println("having dinner!");
    }
    public void sleep() {
        System.out.println("sleep!");
    }
}
public class Task {
    public static void main(String[] args) {
        Person person = new Person();//Instantiate objects through new
        person.eat();//Member method calls need to be called by reference to the object
        person.sleep();
        //Generate object instantiation object
        Person person2 = new Person();
        Person person3 = new Person();
    }
}

The operation results are as follows:

matters needing attention:

  • The new keyword is used to create an instance of an object.
  • Use. To access properties and methods in an object.
  • Multiple instances of the same class can be created.

3. Member of class

Class members can include the following: fields, methods, code blocks, internal classes, interfaces, and so on.

3.1 field / attribute / member variable

In a class, but a variable defined outside a method. We call it "field" or "attribute" or "member variable" (all three names can be used, which are generally not strictly distinguished). It is used to describe what data is contained in a class.
Code example:

class Person {
    public int age;//field
    public String name;

}
public class Task {
    public static void main(String[] args) {
        Person person = new Person();
        System.out.println(person.name);
        System.out.println(person.age);
    }
}

The results are as follows:

matters needing attention:

  • Use. To access the fields in the object;
  • "Access" includes both read and write;
  • For the field of an object, if the initial value is not displayed, a default initial value will be set.

Default value rule:

  • For various number types, the default value is 0;
  • For boolean type, the default value is false;
  • For reference types (String, Array, and custom classes), the default value is null.

Know null

Null is a "null reference" in Java, which means that it does not reference any object. It is similar to the null pointer in C language. If NULL is operated on, an exception will be thrown.

Code example:

class Person {
    public int age;//field
    public String name;

}
public class Task {
    public static void main(String[] args) {
        Person person = new Person();
        System.out.println(person.name.length());//Get string length
    }
}

The results are as follows:

Field local initialization
In many cases, we don't want the field to use the default value, but we need to explicitly set the initial value. Therefore, it can be written as follows:

class Person {
    public int age=18;//field
    public String name="Li Si";

}
public class Task {
    public static void main(String[] args) {
        Person person = new Person();
        System.out.println(person.name);
        System.out.println(person.age);
    }
}

The results are as follows:

3.2 method

Used to describe the behavior of an object.

Code example:

class Person {
    public int age=18;//field
    public String name="Li Si";
    public void show(){
        System.out.println("My name is"+name+",this year"+age+"Years old");
    }
}
public class Task {
    public static void main(String[] args) {
        Person person = new Person();
        person.show();
    }
}

The results are as follows:

The show method here indicates that the Person object has a "show yourself" behavior.
Such a show method is associated with the person instance. If other instances are created, the behavior of show will change.
For example:

Person person2 = new Person();
person2.name = "Li Si";
person2.age = 20;
person2.show()

The results are as follows:

There is also a special method called construction method
The method that will be called automatically when instantiating an object. The method name is the same as the class name, which is used for object initialization
Although we have been able to initialize attributes locally, sometimes more complex initialization logic may be required, so the constructor can be used
The syntax of the construction method will be described in detail later.

3.3 static keyword

  • Modifier attribute
  • Modification method
  • Code block
  • Modifier class

a) Decorated attributes: Java static attributes are related to classes and independent of specific instances. In other words, different instances of the same class share the same static attribute.

class TestDemo{
    public int a;
    public static int count; }
public class Task{
    public static void main(String[] args) {
        TestDemo t1 = new TestDemo();
        t1.a++;
        TestDemo.count++;
        System.out.println(t1.a);
        System.out.println(TestDemo.count);
        System.out.println("============");
        TestDemo t2 = new TestDemo();
        t2.a++;
        TestDemo.count++;
        System.out.println(t2.a);
        System.out.println(TestDemo.count);
    }
}

The results are as follows:

Seeing the running result, some partners can't help wondering why the second output of count is 2, shouldn't it be 1? The reason for this result is that count is modified by static. All classes share it and do not belong to an object. It belongs to a class. The access method is: class name. Attribute.

b) Modification method
If you apply the static keyword to any method, this method is called a static method.

  • Static methods belong to classes, not objects that belong to classes.
  • Static methods can be called directly without creating an instance of the class.
  • Static methods can access static data members and change the values of static data members.

Code example:

class TestDemo{
    public int a;
    public static int count;
    
    public static void change() {
        count = 100;
        //a = 10; error non static data members cannot be accessed
   }
}
public class Task{
public static void main(String[] args) {
        TestDemo.change();//Can be called without creating an instance object
        System.out.println(TestDemo.count);   
   }
}

The results are as follows:

Note 1: static methods have nothing to do with instances, but are related to classes. Therefore, this leads to two situations:

  • Static methods cannot directly use non static data members or call non static methods (both non static data members and methods are instance related).
  • This and super keywords cannot be used in a static context (this is the reference of the current instance, super is the reference of the parent instance of the current instance, and is also related to the current instance).

Note 2:

  • Static is added to all the methods we have written in order to be simple. But in fact, whether a method needs static or not depends on the situation.
  • The main method is a static method.

3.4 summary

Let's analyze the memory layout through the following code:

class Person {
    public int age;//Instance variables are stored in objects
    public String name;//Instance variable
    public String sex;//Instance variable
    public static int count;//Class variables are also called static variables. They have been generated during compilation. They belong to the class itself and have only one copy. Store in method area
    public final int SIZE = 10;//What is modified by final is called a constant, which also belongs to an object. It is modified by final and cannot be changed later
    public static final int  COUNT = 99;//Static constants belong to the class itself. Only one is modified by final and cannot be changed later
    //Instance member function
    public void eat() {
        int a = 10;//local variable
        System.out.println("eat()!");
    }
    //Instance member function
    public void sleep() {
        System.out.println("sleep()!");
    }
    //Static member function
    public static void staticTest(){
        //Non static members cannot be accessed
        //sex = "man"; error
        System.out.println("StaticTest()");
    }
}
public class Task{
    public static void main(String[] args) {
        //Generate object instantiation object
        Person person = new Person();//person is a reference to the object
        System.out.println(person.age);//The default value is 0
        System.out.println(person.name);//The default value is null
        //System.out.println(person.count);// There will be a warning!
        //Correct access method:
        System.out.println(Person.count);
        System.out.println(Person.COUNT);
        Person.staticTest();
        //Summary: all methods or properties modified by static do not depend on objects.
        person.eat();
        person.sleep();
    }
}

The results are as follows:

Memory layout of data attributes:

4. Encapsulation

What is encapsulation?

< < code encyclopedia > > starts by discussing a problem: the essence of software development is the management of program complexity. If the complexity of a software code is too high, it can not be maintained.
How to manage complexity? Encapsulation is the most basic method. When we write code, we often involve two roles: class implementer and class caller.
The essence of encapsulation is that the caller of a class does not have to know much about how the implementer of the class implements the class, as long as he knows how to use the class. This reduces the learning and use cost of class users, thus reducing the complexity.

4.1 private implementation encapsulation

The two keywords private/ public represent "access control".

  • The member variable or member method modified by public can be directly used by the caller of the class.
  • The member variable or member method modified by private cannot be used by the caller of the class.

In other words, the user of a class does not need to know or pay attention to the private members of a class, so that the class caller can use the class at a lower cost.

Direct use of public code example:

class Person {
    public String name = "Zhang San";
    public int age = 19; }
public class Task {
    public static void main(String[] args) {
        Person person = new Person();
        System.out.println("My name is" + person.name + ", this year" + person.age + "year");
    }
}

The results are as follows:

be careful:

  • Such code causes the user of the class (the code of the main method) to understand the internal implementation of the Person class before they can use this class. The learning cost is high.
  • Once the implementer of the class modifies the code (for example, changing name to myName), the user of the class needs to modify his code on a large scale, and the maintenance cost is high.

Therefore, we can use private to encapsulate attributes and provide public methods for class callers.
Code examples are as follows:

class Person {
    private String name = "Zhang San";
    private int age = 19;
    public void show(){
        System.out.println("My name is" + name + ", this year" + age + "year");
    }
}
public class Task {
    public static void main(String[] args) {
        Person person = new Person();
        person.show();
    }
}

The results are as follows:

  • At this time, the field has been decorated with private. The caller of the class (in the main method) cannot use it directly. Instead, it needs to use the show method. At this time, the user of the class does not need to understand the implementation details of the Person class.
  • At the same time, if the implementer of the class modifies the name of the field, the caller of the class does not need to make any modification (the caller of the class cannot access fields such as name and age at all).

So the problem comes ~ ~ if the implementer of the class changes the name of the public method show, isn't it that the caller of the class still needs to modify a lot of code?
This is true, but it usually rarely happens. The design of general classes requires that the public methods provided by classes can be relatively stable and should not change frequently. This is especially true for some classes in the basic library. The compatibility problem should be considered carefully every time the interface changes

matters needing attention:

  • private can modify not only fields, but also methods.
  • Generally, we will set the field to private attribute, but whether the method needs to be set to public depends on the specific situation. Generally, we want a class to provide only "necessary" public methods, rather than setting all methods to public.

4.2 getter and setter methods

When we use private to decorate a field, we can't use this field directly.

Code example:

class Person {
    private String name = "Zhang San";
    private int age = 19;
    public void show(){
        System.out.println("My name is" + name + ", this year" + age + "year");
    }
}
public class Task {
    public static void main(String[] args) {
        Person person = new Person();
        person.age=20;
        person.show();
    }
}

The results are as follows:

At this time, if you need to get or modify the private property, you need to use the getter / setter method.
Code example:

class Person {
    private String name;//Instance member variable
    private int age ;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        //name=name;  // You can't write that
        this.name = name;//this reference represents the object that calls the method. It is also used to better distinguish member variables from local variables
    }

    public void show(){
        System.out.println("name:" + name + " age:" + age );
    }
}
public class Task {
    public static void main(String[] args) {
        Person person = new Person();
        person.setName("marry");//Assign a value to the name attribute
        System.out.println(person.getName());
        person.show();
    }
}

The results are as follows:

matters needing attention:

  • getName is the getter method, which means to get the value of this member.
  • setName is the setter method, which means to set the value of this member.
  • When the formal parameter name of the set method is the same as the name of the member attribute in the class, if this is not used, it is equivalent to self assignment. This represents the reference of the current instance.
  • Not all fields must provide setter / getter methods, but which method to provide should be determined according to the actual situation.
  • In IDEA, you can use alt + insert (or alt + F12) to quickly generate setter / getter methods. In VSCode, you can use the right mouse button menu - > source code operation to automatically generate setter / getter methods.

5. Construction method

5.1 basic grammar

Construction method is a special method. When a new object is instantiated with the keyword new, it will be automatically called to complete the initialization operation.
new execution process:

  • Allocate memory space for objects
  • Call the constructor of the object

rule of grammar:

  • The method name must be the same as the class name
  • Constructor has no return value type declaration
  • There must be at least one construction method in each class (if there is no explicit definition, the system will automatically generate a parameterless construction)

matters needing attention:

  • If no constructor is provided in the class, the compiler generates a constructor without parameters by default.
  • If a constructor is defined in a class, the default parameterless constructor will no longer be generated.
  • The construction method supports overloading. The rules are consistent with the overloading of ordinary methods.

Code example:

class Person {
    private String name ;//Instance member variable
    private int age ;
    private String sex;
    //Default constructor construction object
    public Person(){
        this.name="mary";
        this.age=18;
        this.sex="female";
    }
    //Constructor with 3 arguments
    public Person(String name,int age,String sex){
        this.name=name;
        this.age=age;
        this.sex=sex;
    }
    public void show(){

       System.out.println("name:" + name + " age:" + age +" sex:"+sex);
    }
}
public class Task {
    public static void main(String[] args) {
        Person person1 = new Person();//Call the constructor without parameters. If the program does not provide it, it will call the constructor without parameters
        person1.show();
        Person person2=new Person("xiaohan",20,"female");//Call the constructor with 3 parameters
        person2.show();
    }
}

Operation results:

5.2 this keyword

This represents the current object reference (note that it is not the current object). You can use this to access the fields and methods of the object.
Code example:

class Person {
    private String name ;//Instance member variable
    private int age ;
    private String sex;
    //Default constructor construction object
    public Person(){
       //this calls the constructor
        this("bit",12,"woman");//It must be displayed on the first line
    }
    //The relationship between these two constructors is overloaded
    public Person(String name,int age,String sex){
        this.name=name;
        this.age=age;
        this.sex=sex;
    }
    public void show(){

        System.out.println("name:" + name + " age:" + age +" sex:"+sex);
    }
}
public class Task {
    public static void main(String[] args) {
        Person person= new Person();//Calling a constructor without parameters 
        person.show();
    }
}

The results are as follows:

Through the above running results, we will find that:

Inside the constructor, we can use the this keyword. The constructor is used to construct the object. Before the object is constructed, we use this. Does this still represent the current object? Of course not. This represents the reference of the current object.

6. Recognize code blocks

Fields are initialized in the following ways:

  1. Local initialization
  2. Initialize with constructor
  3. Use code block initialization

The first two methods have been studied earlier in this article. Next, we will introduce the third method, which uses code block initialization.

6.1 what is a code block

A piece of code defined with {}.

According to the location and keywords defined by the code block, it can be divided into the following four types:

  • Common code block
  • Tectonic block
  • Static block
  • Synchronous code block (not discussed at present due to limited level)

6.2 common code block

Normal code block: a code block defined in a method
Code example:

public class Task {
    public static void main(String[] args) {
        {   //The block defined directly with {} is a normal method block
            int x=10;
            System.out.println("x1= "+x);
        }
        int x=100;
        System.out.println("x2= "+x);
    }
}

The results are as follows:

This usage is rare

6.3 building blocks

**Construction block: * * code block defined in class (without modifier). Also known as: instance code block. Construction code blocks are generally used to initialize instance member variables.
Code example:

class Person{
    private String name;//Instance member variable
    private int age;
    private String sex;

    public Person() {
        System.out.println("I am Person init()!");
    }

    //Instance code block
    {
        this.name = "bit";
        this.age = 12;
        this.sex = "woman";
        System.out.println("I am instance init()!");
    }

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

}
public class Task {
    public static void main(String[] args) {
        Person person=new Person();
        person.show();
    }
}

The results are as follows:

Note: instance code blocks take precedence over constructor execution.

6.4 static code block

Code blocks defined using static. Generally used to initialize static member properties.
Code example:

class Person{
    private String name;//Instance member variable
    private int age;
    private String sex;
    private static int count = 0;//Static member variables are shared by classes in the data method area

    public Person(){
        System.out.println("I am Person init()!");
    }

    //Instance code block
    {
        this.name = "bit";
        this.age = 12;
        this.sex = "man";
        System.out.println("I am instance init()!");
    }

    //Static code block
    static {
        count = 10;//Only static data members can be accessed
        System.out.println("I am static init()!");
    }

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

}
public class Task {
    public static void main(String[] args) {
        Person person=new Person();
        Person person1=new Person();//Will static code blocks still be executed?
    }
}

The results are as follows:

matters needing attention:

  • No matter how many objects are generated, the static code block will be executed only once and first.
  • After the static code block is executed, the instance code block (construction block) is executed, and then the constructor is executed.

7. Supplementary notes

7.1 toString method

We have just noticed that we have implemented the show function when printing the properties of objects. In fact, we don't have to. Next, let's look at some sample code:
Example code:

class Person {
    private String name;
    private int age;
    public Person(String name,int age) {
        this.age = age;
        this.name = name;
    }
    public void show() {
        System.out.println("name:"+name+" " + "age:"+age);
    }
}
public class Task {
    public static void main(String[] args) {
        Person person = new Person("mary",19);
        person.show();
        //We found that the hash value of an address is printed here. The reason: the toString method of Object is called
        System.out.println(person);
    }
}

The results are as follows:

You can use methods like toString to automatically convert objects to strings.
Code example:

class Person {
    private String name;
    private int age;
    public Person(String name,int age) {
        this.age = age;
        this.name = name;
    }
    public void show() {
        System.out.println("name:"+name+" " + "age:"+age);
    }
    //Override the toString method of Object
    @Override
    public String toString() {
        return "Person{" +
                "name= '" + name + '\'' +
                ", age=" + age +
                '}';
    }
}
public class Task {
    public static void main(String[] args) {
        Person person = new Person("mary",19);
        person.show();
        //We found that the hash value of an address is printed here. The reason: the toString method of Object is called
        System.out.println(person);
    }
}

The results are as follows:

toString method in the original Object:

public String toString() {
        return getClass().getName() + "@" + Integer.toHexString(hashCode());
    }

matters needing attention:

  • The toString method will be called automatically when printing LN.
  • The operation of converting an object into a string is called serialization.
  • ToString is the method provided by the Object class. The Person class created by ourselves inherits from the Object class by default. You can override the toString method to implement our own version of the conversion string method.
  • @Override is called "Annotation" in Java. Here @ override means that the toString method implemented below is a method that overrides the parent class.
  • IDEA quickly generates the toString method shortcut key of Object: alt+f12(insert).

7.2 anonymous objects

Anonymity simply means an object without a name

  • Objects that are not referenced are called anonymous objects.
  • Anonymous objects can only be used when creating objects.
  • If an object is used only once and does not need to be used later, consider using anonymous objects.

Code example:

class Person {
    private String name;
    private int age;
    public Person(String name,int age) {
        this.age = age;
        this.name = name;
    }
    public void show() {
        System.out.println("name:"+name+" " + "age:"+age);
    }
}
public class Task {
    public static void main(String[] args) {
        new Person("mary",20).show();
    }
}

The results are as follows:

7.3 summary of key contents of this chapter

  1. A class can produce countless objects. A class is a template and an object is a concrete instance.
  2. The attributes defined in class can be roughly divided into several categories: class attributes and object attributes. The data attributes modified by static are called class attributes, and the methods modified by static are called class methods. The feature is that they do not depend on objects. We can call their attributes or methods only through the class name.
  3. Static code block takes precedence over instance code block, and instance code block takes precedence over constructor.
  4. this keyword represents the reference of the current object. Is not the current object.

Tags: Java Back-end

Posted on Wed, 10 Nov 2021 22:42:52 -0500 by djcee