Java -- super detailed summary of classes and objects

Classes and objects

1. Preliminary understanding 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 a thing into different objects and completes it by the interaction between objects.

Facing the process, we pay attention to the process. Just like washing clothes by hand, we need to use a basin to receive water, then put in clothes, then put in washing powder, then rub it by hand, and then screw it dry and dry it.

Object oriented focuses on objects, just like we use the washing machine to wash clothes. As long as we put clothes and washing clothes into the washing machine and dry them, we don't have to worry about how the washing machine washes clothes.

2. Class and class instantiation

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

Class is equivalent to a template, and the object is the 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.

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

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.

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.
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 DemoTest {
    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

  1. The new keyword is used to create an instance of an object.

  2. Use. To access properties and methods in an object.

  3. Multiple instances of the same class can be created.

3. Members of the class

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

Here we focus on the first three.

3.1 field / attribute / member variable

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

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

public class TestDemo {
    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

  1. Use. To access the fields of the object.
  2. Access includes both read and write.
  3. For the field of an object, if the initial value is not explicitly set, a default initial value will be set.

Default value rule

The default value is 0 for various numeric types.

For boolean types, the default value is false.

For reference types (String,Array, and custom classes), the default value is null

Person person = null;
//This reference does not point to any object

Person person = new Person();
Person person2=person;
//The reference of person2 points to the object pointed to by the reference of person

Person person = new Person();
person = new Person();
person = new Person();
person = new Person();
//A reference cannot point to multiple objects at the same time. It actually points to the last object

Field local 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, which can be written as follows:

class Person{
    public String name = "ljj";    
    public int age = 18;
}

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

//results of enforcement
ljj
18

3.2 method

Used to describe the behavior of an object.

class Person{
    public String name = "ljj";    
    public int age = 18;
    
    public void show(){
       System.out.println("My name is"+name+",this year"+age+"year"); 
    }
}

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

//results of enforcement
 My name is ljj,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;
person.show();

//results of enforcement
 My name is Li Si. I'm 20 years old

3.3 static keyword

  1. Modifier attribute
  2. Modification method
  3. Code block
  4. Modifier class

a) Decorated attributes, Java static attributes are related to classes and have nothing to do with specific instances. In other words, different instances of the same class share a static property.

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

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

The output result is:

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

b) Modification method

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

  1. Static methods belong to classes, not objects that belong to classes.
  2. Static methods can be called directly without creating an instance of the class.
  3. Static methods can access static data members and change the values of static data members.
class TestDemo1{
    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 TestDemo {
    public static void main(String[] args) {
        TestDemo1.change();    //  Can be called without creating an instance object
        System.out.println(TestDemo1.count);
    }
}

Output results:

100

Note 1: static methods are not related to instances, but to classes. This leads to two situations:

  1. Static methods cannot directly use non static data members or call non static methods (both non static data members and methods are instance related).
  2. 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:

  1. The methods we used to write are unified with static for simplicity. But in fact, whether a method needs static or not depends on the situation.
  2. The main method is a static method.

4. Packaging

The essence of software development is the management of program complexity. If the complexity of a software code is too high, it cannot be maintained. How to manage complexity? Encapsulation is the most basic method.

When we write code, we often involve two roles: the implementer of the class and the caller of the class.

The essence of encapsulation is that the caller of a class does not have to know how the implementer of the class implements the class, as long as he knows how to use it.

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.

Use public directly

class Person{
    public String name = "ljj";    
    public int age = 18;
    
public class TestDemo {
    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 ljj,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 he can use this class, which has a high learning cost.

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 = "ljj";    
    private int age = 18;
    
    public void show(){
        System.out.println("My name is"+person.name+",this year"+person.age+"year");
    }
}

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

//results of enforcement
 My name is ljj,He is 18 years old

At this time, the field has been decorated with private, and the caller of the class (in the main method) cannot use it directly. You need to use the show method. At this point, the user of the class does not have 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).

matters needing attention

  1. private can modify not only fields, but also methods.
  2. 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 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 = "ljj";    
    private int age = 18;
    
    public void show(){
        System.out.println("My name is"+person.name+",this year"+person.age+"year");
    }
}

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

//Compilation error
java: age Can be in Person Medium access private

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 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 class TestDemo {
    public static void main(String[] args) {
        Person person = new Person();
        person.setName("ljj");
       String name = person.getName();
        System.out.println(name);
        person.show();
    }
}

//Operation results
ljj
name:ljj age:0

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 member attribute name in the class, if this is not used, it is equivalent to assignment. This represents the reference of the current instance.

Not all fields must be provided with setter/getter methods, but which method should be provided 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

  1. Allocate memory space for objects

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

  1. If no constructor is provided in the class, the compiler generates a constructor without parameters by default.

  2. If a constructor is defined in a class, the default parameterless constructor will no longer be generated.

  3. The construction method supports overloading, and the rules are consistent with those 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 = "ljj";
        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 TestDemo {
    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
        p1.show();
        Person person2 = new Person("Li Si",80,""Male");    //Calling a constructor without parameters  
        p2.show();
    }
}

//results of enforcement
name:ljj age:10 sex:male
name:Li Si age:80 sex:male

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.

class Person{
    private String name;    //  Instance member variable    
    private int age;
   //  Default constructor construction object
    public Person(){
        //  this calls the constructor
        this("bit",12,"man");    //  Must be explicitly placed 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 TestDemo {
    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

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 using {}.

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

  1. Common code block
  2. Tectonic block
  3. Static block
  4. Synchronous code block

6.2 common code block

Normal code block: a code block defined in a method

public class TestDemo {
    public static void main(String[] args) {
        {
            //  Use {} directly to define common method blocks
            int x = 10;
            System.out.println("x1 = "+x);
        }
        int x = 100;
        System.out.println("x2 = "+x);
    }
}

//results of enforcement
x1 = 10
x2 = 100

6.3 building blocks

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 = "ljj";
        this.age = 18;
        this.sex = "man";
        System.out.println("I am instance init()!");
    }
    
     public void show(){
        System.out.println("name:"+name+" age:"+age+"sex:"+sex);
    }
}

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

//Operation results
I am instance init()!
I am Person init()!
name:ljj age:18 sex:man

Note: instance code blocks take precedence over constructor execution.

6.4 static code block

Code blocks defined with static are 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 = "ljj";
        this.age = 18;
        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 instance init()!");
    }
    
    public void show(){
        System.out.println("name:"+name+" age:"+age+"sex:"+sex);
    }
}

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

matters needing attention

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

Keywords: Java Back-end

Added by gmann001 on Wed, 03 Nov 2021 04:50:35 +0200