Classes and objects in java (key points) are super detailed

Classes and objects in java

1. Preliminary cognition of class and object

2. Instantiation of classes and objects

3. Member of class

3.1,Fields, properties, member variables
3.2,method
3.3,static keyword
3.4,Summary

4. Encapsulation

4.1,private Implementation encapsulation
4.2,getter and setter method

5. Construction method

5.1,Basic method
5.2,this keyword

6. Recognize code blocks

6.1,What is a code block
6.2,Common code block
6.3,Construct code block
6.4,Static code block

7. Anonymous object

1. 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 function.
Object oriented focuses on objects, that is, the subjects involved in the process. It is to connect each functional realization through logic
Object oriented focuses on objects, that is, the subjects involved in the process. It is to connect each functional realization through logic
Process oriented: 1. Open the refrigerator 2. Put the elephant in 3. Close the refrigerator object-oriented: opening, storing and closing the refrigerator are the operation and 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, etc
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

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. Instantiation of classes and objects

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

class TestStu{
    public String name;//Member variable, attribute, field
    public int age;//Member variable, attribute, field
	public void add(){
        System.out.println("This is a method");
    }
}
public class TestDome {
    public static void main(String[] args) {
        TestStu teststu = new TestStu();
        System.out.println(teststu.name);
    }
}

Class represents the keyword of the class, TestStu represents the name of the class, and name and age represent the member variables of the class
The elements in the class are called member attributes. The functions in a class are called member methods
matters needing attention
Different from the method written before, the method written here does not take the static keyword. We will explain in detail what static does later

TestStu teststu = new TestStu(); It means instantiating an object. The reference teststu points to the object new teststu(), which has two attributes: name and age.

Class instantiation
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. 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 is equivalent to a class of things with the same properties and characteristics: for example
    A BMW (this is an object) and a Mercedes Benz (this is an object) can be human. They all have lights and seats (this is the same attribute they have). Of course, they also have attributes that are not available to another object (for example, BMW has a sunroof, while Mercedes Benz does not)
    Objects are abstracted from classes, and this process is instantiation

Look at the code below

class TestStu{
    public String name = "zhangsan ";//Member variable, attribute, field
    public int age;//Member variable, attribute, field

    public void add(){   //Member method
        System.out.println("This is a method");
    }
}
public class TestDome {
    public static void main(String[] args) {
        TestStu teststu1 = new TestStu();//This is the first object
        System.out.println(teststu1.name);
        System.out.println("=============");
        TestStu teststu2 = new TestStu();//This is the second object
        System.out.println(teststu2.name);
    }
}


Two objects are generated through new instantiation. name and age are their common attributes

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

3. Member of class

3.1,Fields, properties, member variables

Class members can include the following: fields, methods, code blocks, internal classes and interfaces
In the class, but the variables defined outside the method. Such variables are called "field" or "attribute" or "member variable" (all three names can be used, which are generally not strict)
(case Division)

Used to describe what data is contained in a class
For example: to describe students, we can describe them by their names, ages, student numbers, etc. These are different for each student, so there are many students who can have different speeds per second

class TestStu{
    public String name = "zhangsan ";//Member variable, attribute, field
    public int age = 18;//

    public void add(){   //Member method
        System.out.println("This is a method");
    }
}

matters needing attention
Use. To access the fields of an 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 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 nul

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 TestStu{
    public int age = 18;//
    public String name;
    public void add(){   //Member method
        System.out.println("This is a method");
    }
}

public class TestDome {
    public static void main(String[] args) {
        TestStu teststu1 = new TestStu();
        System.out.println(teststu1.name.length());
        System.out.println("=============");
        TestStu teststu2 = new TestStu();
        System.out.println(teststu2.name);
    }
}

Field initialization
In many cases, we don't want to use the default value for the field, but we need to explicitly set the initial value. You can do this:
However, it is not recommended to write this (because you initialize in the class. When instantiating multiple objects, each object has the same attribute, for example: both students are 18 years old and are called Zhang San!! this is not good). We will talk about it later

class TestStu{
    public String name = "zhangsan ";//Member variable, attribute, field
    public int age = 18;//
  
    public void add(){   //Member method
        System.out.println("This is a method");
    }
}

public class TestDome {
    public static void main(String[] args) {
        TestStu teststu1 = new TestStu();
        System.out.println(teststu1.name.length());
        System.out.println("=============");
        TestStu teststu2 = new TestStu();
        System.out.println(teststu2.name);
    }
}

3.2 method
This is the method we talked about
Used to describe the behavior of an object
The method of the object is called through the reference teststu

class TestStu{
    public String name ;//Member variable, attribute, field
    public int age = 18;

    public void eat(){   //Member method
        System.out.println(name+"be at  table");
    }
    public void sleep(){
        System.out.println(name+"sleeping");
    }
}
public class TestDome {
    public static void main(String[] args) {
        TestStu teststu = new TestStu();
        teststu.name = "Zhang San";
        teststu.eat();
        teststu.sleep();
    }
}


3.3 static keyword
1. Modifier attribute
2. Modification method
3. Code block (introduced in this courseware)

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

class TestDate{
    public int a;
    public static int count;
}

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


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 their values

class TestD{
    public int a;
    public static int cont = 0;

    public static void func(){
        cont = 99;
        System.out.println("Static method"+" "+cont);
    }
}

public class TestDome {
    public static void main(String[] args) {
        TestD t1 = new TestD();
        System.out.println(t1.a);
        TestD.func();
    }
}    


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)

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

3.4 summary
Observe the following code to analyze the memory layout

4. Encapsulation

What is encapsulation?

< < code encyclopedia > > at the beginning, we discuss a problem: the essence of software development is the management of program complexity. If a software code is complex
If the complexity is too high, it cannot be maintained. How to manage the 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 class implementer 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"
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 it at a lower cost
Cost to use class

Directly use public decoration:

class Stu{
    public String name = "Zhang San";
    public int age = 18;
}

public class TestDome {
    public static void main(String[] args) {
        Stu stu = new Stu();
        System.out.println(stu.name+" "+stu.age);

    }
}

Such code causes the user of the class (the code of the main method) to understand the internal implementation of Stu class before he can use this class. The learning cost is low
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
High maintenance cost.
How to solve this problem??
getter and setter methods

matters needing attention
private can modify not only fields, but also methods
Usually, we will set the field to private attribute, but whether the method needs to be set to private depends on the specific situation
It is expected that a class only provides "necessary" public methods, rather than setting all methods as public

4.2. getter and setter methods
When we use private to modify a field, we can't directly use this field. At this time, the compilation will report an error

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

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

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }
}

public class TestDome {
    public static void main(String[] args) {
        Stu stu = new Stu();
        stu.setAge(99);
        stu.setName("WangTwo ");
        System.out.println(stu.getAge()+" "+stu.getName());

    }
}


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 current instance
References to
Not all fields must provide setter / getter methods, but which method should be provided according to the actual situation
Quick production getter / setter method

5. Construction method

5.1,Basic method
 Construction method is a special method, Use keywords new Automatically called when a new object is instantiated, Used 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.Constructor has no return value type declaration
		3.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 the class, the default parameterless constructor will no longer be generated.
		The constructor supports overloading. The rules are consistent with the overloading of ordinary methods

class SutD{
    public int age;
    public String name;
    public SutD(){
        System.out.println("This is a construction method without parameters");
    }
    public SutD(int a){
        System.out.println("This is a construction method with one parameter");
    }
    public SutD(int a,String b){
        System.out.println("This is a construction method with two parameters");
    }
}

public class TestDome {
    public static void main(String[] args) {
        SutD stud = new SutD();//This is a construction method without parameters
        SutD stud1 = new SutD(200);//This is a construction method with one parameter
        SutD stud2 = new SutD(50,"Zhang San");//This is a construction method with two parameters
    }
}


5.2 this keyword
This indicates 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

class SutD{
    public int age = 20;
    public String name;
    public SutD(){
        this(20);//This must be at the front
        System.out.println("This is a construction method without parameters");
    }
    public SutD(int a){
        System.out.println("This is a construction method with one parameter"+age);
    }
    public SutD(int a,String b){
        System.out.println("This is a construction method with two parameters");
    }
}

public class TestDome {
    public static void main(String[] args) {
        SutD stud = new SutD();//This is a construction method without parameters
        SutD stud1 = new SutD(200);//This is a construction method with one parameter
        SutD stud2 = new SutD(50,"Zhang San");//This is a construction method with two parameters
    }
}

When this is not at the front, an error will be reported

We will find that inside the constructor, we can use the this keyword. The constructor is used to construct the object. The object has not been constructed yet,
We used 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 before. Next, we 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 (to be discussed later in the multi threading section)


When I swap the fast positions of static code blocks and normal code, the result is different


Static code blocks are executed without instantiating objects

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. Anonymous object

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

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 Main {
	public static void main(String[] args) {
	new Person("caocao",19).show();//Calling methods through anonymous objects
	}
}

Summary of key contents
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
Methods are called class methods, which are characterized by being independent of objects. We can call their properties or methods only through the class name.
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.

Keywords: Java Back-end

Added by stirton on Thu, 04 Nov 2021 10:35:58 +0200