[Java] after a long time, you can finally give yourself new objects -- Java classes and objects

Keywords: Java Back-end

🗽 Preliminary cognition of class and object

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 the function.
[object oriented] focuses on the object, that is, the subject involved in the process. It is to connect each functional realization through logic

Facing the process: 1. Open the refrigerator 2. Put the elephant in 3. Close the refrigerator
Object oriented: opening, storing and closing the refrigerator are the operation of the refrigerator and the behavior of the refrigerator. The refrigerator is an object, so as long as the functions of the refrigerator are operated, they should be defined in the refrigerator.

[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 and so on
2. Class is the general name of 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.

[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)
During development: find objects, build objects, use objects, and maintain the relationship between objects.
In the later learning process, we will conduct in-depth study on these three points.
In short, object - oriented is a way of using code (class) to describe things in the objective world
A class mainly includes [attribute] and [behavior] of a class of things

🗽 Classes and instantiation of 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. Let's look at the following simple declaration of a class.
Basic grammar

// 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.

Examples are as follows:

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!");  
}

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

🗽 Class instantiation

The process of creating objects with class types is called class instantiation
1. A class is just a model that defines the members of the class
2. A class can instantiate multiple objects. The instantiated objects occupy the actual physical space and store class member variables
3. Make an analogy. Class instantiation of objects is like building a house using architectural design drawings in reality. Class is like design drawings. It only designs what is needed, but there is no physical building. Similarly, class is only a design. The instantiated objects can actually store data and occupy physical space

class Person {//Class (person)
   public int age;//attribute 
   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 Main{
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 output result is:
having dinner!
sleep

matters needing attention

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

🗽 Member of class

Class members can include the following: fields, methods, code blocks, internal classes, interfaces, and so on.
Here we focus on the first three

⭐ Field / attribute / member variable

In a class, but a variable defined outside the method. Such a variable is called "field" or "attribute" or "member variable" (all three names can be used, which are generally not strictly distinguished). It is used to describe the data contained in a class

class Person {
   public String name;   // field
   public int age; }
class Test {
   public static void main(String[] args) {
    Person person = new Person();
       System.out.println(person.name);
       System.out.println(person.age);
  }
}
// results of enforcement
null
0

matters needing attention

  • Use [.] to access the field of the object. "Access" includes both read and write
  • If the initial value is not explicitly set for an object field, a default initial value will be set

Default value rule

  • For member variables, no public or privat e modification is added, and the default public modification is used
  • For various numeric types, the default value is 0
  • For boolean types, 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 no object is referenced. It is similar to a null pointer in C language. If NULL is operated on, an exception will be thrown

class Person {
   public String name;
   public int age; }
class Test {
   public static void main(String[] args) {
       Person person = new Person();
       System.out.println(person.name.length());   // Get string length
  }
}
// results of enforcement
Exception in thread "main" java.lang.NullPointerException
       at Test.main(Test.java:9)

Field local initialization
Many times, we don't want to use the default value for the field, but we need to explicitly set the initial value. It can be written as follows:

class Person {
   public String name = "Zhang San";
   public int age = 18; }
class Test {
   public static void main(String[] args) {
       Person person = new Person();
       System.out.println(person.name);
       System.out.println(person.age);
  }
}
// results of enforcement
 Zhang San
18

⭐ method

This is the method we talked about (a function similar to C)
Used to describe the behavior of an object

class Person {
    public int age = 18;
    public String name = "Zhang San";
    
    public void show() {
   System.out.println("My name is" + name + ", this year" + age + "year");
   }
}
class Test {
    public static void main(String[] args) {
        Person person = new Person();
        person.show();
   }
}
// results of enforcement
 My name is Zhang San, He is 18 years old

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

Person person2 = new Person();
person2.name = "Li Si";
person2.age = 20;
person2.show()
    
// results of enforcement
 My name is Li Si, I'm 20 years old

⭐ static keyword

1. Modifier attribute
2. Modification method
3. Code block (described in this article)
4. Modifier class (the inner class will be described later)

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 Main{
   
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 output result is:

1
1

============
1
2

Sample code memory parsing:
count is modified by static and public and shared by all classes
And it does not belong to an object. 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.

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 Main{
public static void main(String[] args) {
       TestDemo.change();//Can be called without creating an instance object
       System.out.println(TestDemo.count);   
  }
} 

Output results:
100

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 for simplicity. But in fact, whether a method needs static or not depends on the situation
  • The main method is a static method

⭐ Summary

Observe the following code and analyze the memory layout

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 Main{
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 output result is:

0
null
0
99
StaticTest()
eat()!
sleep()!

Memory layout of data attributes:

🗽 encapsulation

⭐ private implementation encapsulation

The two keywords private/ public represent "access control"

  • Member variables or member methods modified by public can be directly used by class callers
  • A 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

Use public directly

class Person {
public String name = "Zhang San";
public int age = 18; }
class Test {
   public static void main(String[] args) {
      Person person = new Person();
      System.out.println("My name is" + person.name + ", this year" + person.age + "year");
  }
}
// results of enforcement
 My name is Zhang San, He is 18 years old
  • 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

Example: use private to encapsulate attributes and provide public methods for class callers

class Person { 
private String name = "Zhang San"; 
private int age = 18; 

public void show() { 
System.out.println("My name is" + name + ", this year" + age + "year"); 
} 
} 
class Test { 
public static void main(String[] args) { 
Person person = new Person(); 
person.show(); 
} 
} 
// results of enforcement
 My name is Zhang San, He is 18 years old
  • 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 know 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 (at this time, the caller of the class cannot access fields such as name and age)

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

⭐ 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 = 18; 

public void show() { 
System.out.println("My name is" + name + ", this year" + age + "year"); 
} 
}
class Test { 
public static void main(String[] args) { 
Person person = new Person(); 
person.age = 20; 
person.show(); 
} 
} 
// Compilation error
Test.java:13: error: age Can be in Person Medium access private 
person.age = 20; 
^ 
1 Errors

At this time, if you need to [get or modify this private attribute], you need to use the getter / setter method
Code example

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

public void setName(String name){ 
//name = name;// You can't write that
this.name = name;//this reference represents the object that calls the method
} 
public String getName(){ 
return name; 
} 

public void show(){ 
System.out.println("name: "+name+" age: "+age); 
} 
} 
public static void main(String[] args) { 
Person person = new Person(); 
person.setName("caocao"); 
String name = person.getName(); 
System.out.println(name); 
person.show(); 
} 
// Operation results
caocao 
name: caocao age: 0 

matters needing attention
1. getName is the getter method, which means to get the value of this member
2.setName is the setter method, which means to set the value of this member
3. 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
4. Not all fields must be provided with setter / getter methods, but which method should be provided according to the actual situation
5. 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

🗽 Construction method

⭐ Basic grammar

Constructor is a special method. When instantiating a new object with the keyword new, it will be called automatically to complete the initialization operation

new execution process

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

rule of grammar

  • 1. The method name must be the same as the class name
  • 2. The constructor has no return value type declaration
  • 3. There must be at least one construction method in each class (if there is no clear 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 constructor 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 = "caocao"; 
this.age = 10; 
this.sex = "male"; 
} 
//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 Main{ 
public static void main(String[] args) { 
Person p1 = new Person();//Call the constructor without parameters. If the program does not provide it, it will call the constructor without parameters
p1.show(); 
Person p2 = new Person("zhangfei",80,"male");//Call the constructor with 3 parameters
p2.show(); 
} 
} 
// results of enforcement
name: caocao age: 10 sex: male
name: zhangfei age: 80 sex: male

⭐ 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

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, "man");//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 Main{ 
public static void main(String[] args) { 
Person person = new Person();//Calling a constructor without parameters
person.show(); 
}
} 
// results of enforcement
name: bit age: 12 sex: man 

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. Although the object has not been constructed, the system has allocated memory space for the object in the first step of the new process, so there are addresses that can be referenced.

🗽 Recognize code blocks

Fields are initialized in the following ways:
1. Local initialization
2. Initialize using the construction method
3. Initialize with code block
The first two methods have been studied before. Next, we introduce the third method, which uses code block initialization

⭐ What is a code block

A piece of code defined using {}
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 (described in detail in the multithreading section later)

⭐ Common code block

This usage is rare

Normal code block: a code block defined in a method.
public class Main{ 
public static void main(String[] args) { 
{ //Directly use {} definition, common method block
int x = 10 ; 
System.out.println("x1 = " +x); 
} 
int x = 100 ; 
System.out.println("x2 = " +x); 
} 
} 
// results of enforcement
x1 = 10 
x2 = 100

⭐ Construct code block

Building blocks: blocks of code defined in a class (without modifiers). Also known as: instance code block. Construction code blocks are generally used to initialize instance member variables.

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 = "man"; 
System.out.println("I am instance init()!"); 
} 

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

} 
public class Main { 
public static void main(String[] args) { 
Person p1 = new Person(); 
p1.show(); 
} 
} 
// Operation results
I am instance init()! 
I am Person init()! 
name: bit age: 12 sex: man 

matters needing attention:
Instance code blocks take precedence over constructor execution.

⭐ Static code block

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

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 Main { 
public static void main(String[] args) { 
Person p1 = new Person(); 
Person p2 = new Person();//Will static code blocks still be executed?
} 
} 

Run result: the static code block only runs once

matters needing attention:
Static code blocks can only manipulate static data
No matter how many objects are generated, the static code block will only be executed once and will be executed first, even if it is not instantiated.
After the static code block is executed, the instance code block (construction block) is executed, and then the constructor is executed.

🗽 Class and object content summary

  • A class can produce countless objects. A class is a template and an object is a concrete instance.
  • 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.
  • Class variables are also called static variables, that is, variables with static added before variables;
    Instance variables are also called object variables, that is, variables without static;
    The difference is:
    The difference between class variable and instance variable is that class variable is shared by all objects. One object changes its value, and the other objects get the changed result;
    The instance variable is private to the object. If an object changes its value, it will not affect other objects;
  • Static code block takes precedence over instance code block, and instance code block takes precedence over constructor.
  • this keyword represents the reference of the current object. Is not the current object.
  • Static data can be accessed directly through classes or through instantiated objects

🌙🌙🌙🌙🌙🌙🌙🌙🌙🌙🌙🌙🌙🌙🌙🌙🌙🌙🌙🌙🌙🌙🌙🌙🌙
        ❤ Originality is not easy. If there is any error, please leave a message in the comment area. Thank you very much ❤
        ❤                 If you think the content is good, it's not too much to give a three company~        ❤
        ❤                              I'll pay a return visit when I see it~                                      ❤
🌙🌙🌙🌙🌙🌙🌙🌙🌙🌙🌙🌙🌙🌙🌙🌙🌙🌙🌙🌙🌙🌙

Posted by edwardsbc on Fri, 29 Oct 2021 16:06:12 -0700