Summary of Java Se and objects

Posted by peddel on Thu, 03 Feb 2022 19:26:29 +0100

catalogue

1, Preliminary understanding of classes and objects

2, Member of class

 1. field

2. Method

3.static keyword

3, Encapsulation

1. What is encapsulation

2.private implementation encapsulation

3.getter and setter methods

4, Construction method

5, Code block

6, Supplement

1.toString method:

 2. Anonymous object

1, Preliminary understanding of classes and objects

1.C language is process oriented, focusing on the process, analyzing the steps to solve the problem, and gradually solving the problem through function call

JAVA yes Based on object-oriented of follow Yes Object, a thing is divided into different objects, which is completed by the interaction between objects. Process oriented focuses on the process, and the behavior involved in the whole process is function. object-oriented Focus on the object, that is, the subject involved in the process of participation. It is to connect each function realization through logic
For example: take washing clothes as an example
Process oriented: people put clothes into the washing machine, pour in washing powder, start the washing machine, and the washing machine will complete the washing process and dry it
Object oriented: the interaction between people, clothes, washing powder and washing machine is completed. People don't need to pay attention to how the washing machine washes clothes and dries clothes

Object oriented is a way of thinking and a kind of thought. For example: concepts and examples. Theory and practice. Name and reality, etc. Its advantage is to make complex things simple, just face an object. Object oriented design holds an important experience: who owns the data and who provides external methods to operate the 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

2. Class is a general term for a class of objects. 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 Java Belong to reference type , Java Use keywords class To declare a class.
Basic syntax for declaring a class:
// Create class
class <class_name>{  
    field;//Member properties
    method;//Member method
}
// Instantiate object
<class_name> <Object name> = new <class_name>();
class by Define the keyword of the class, ClassName Is the name of the class, {} Is the body of the class. The elements in the class are called member attributes. The functions in a class are called member methods
3. Class instantiation
The process of creating objects with class types is called class instantiation
(1) Class only One Model The same thing defines which members a class has
(2) A class can instantiate multiple objects, The instantiated object occupies the actual physical space and stores class member variables. hit For example. Class instantiates an object, just like building a house with architectural design drawings in reality, and class is like design drawings , just design what you need West, but there is no physical building. Similarly, the class is only a design. Only the instantiated object can actually store data and occupy physical space
(3)new Keyword is used to create an instance of an object
(4) Multiple instances of the same class can be created
The following code:
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 Main{
    public static void main(String[] args) {
        Person person = new Person();//Instantiate objects through new
        Person person2 = new Person();//Generate object # instantiate object
        person.eat();//Member method calls need to be called through the reference of the object
        person.sleep();
    }
}

Compile and run the code, and the output is as follows:

having dinner!

sleep

2, Member of class

Class members can include the following: fields, methods, code blocks, internal classes and interfaces. However, this note focuses on the first three

 1. field

In class , However, variables defined outside the method . Such variables are called " field " or " attribute " or " Member variable "( All three titles are OK , (generally not strictly differentiated)
Member variables are divided into ordinary member variables and static member variables. The following classes are ordinary members. Static member variables will be encountered later in the notes
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);
   }
}

Compile and run the code, and the output is as follows:

null

0

(1) use The field of the access object. Access includes both read and write

(2) For the field of an object, if the initial value is not explicitly set , Then a default initial value will be set.
Default 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 null
Many times we don't want fields to use default values , Instead, we need to explicitly set the initial value:
class Person {
    public String name;  
    public int age; 
}
class Test {
    public static void main(String[] args) {
        Person person = new Person();
        person.name = "Zhang San";
        person.age = 18;
        System.out.println(person.name);
        System.out.println(person.age);
   }
}

Compile and run the code, and the output is as follows:

Zhang San

18

In fact, it can also be initialized inside Person, but we don't recommend this, because when we new multiple objects, not every object is called Zhang San, who is 18 years old

2. Method

Used to describe the behavior of an object

Methods are divided into ordinary methods and static methods. The following classes are ordinary methods. Static methods will be encountered later in the notes

class Person {
    public int age;
    public String name;
    public void show() {
   System.out.println("My name is" + name + ", this year" + age + "year");
   }
}
class Test {
    public static void main(String[] args) {
        Person person1 = new Person();
        Person person2 = new Person();
        person1.age = 18;
        person1.name = "Zhang San";
        person2.age = 19;
        person2.name = "Li Si";
        person1.show();
        person2.show();
   }
}

Compile and run the code, and the output is as follows:

My name is Zhang San. I'm 18 years old

My name is Li Si. I'm 19 years old

Here show method , express Person This object has a " Show yourself " act show like this The method is and person Instance associated . If other instances are created , that show Your behavior will change
There is also a special method called Construction method, which will be summarized later in the notes.

3.static keyword

It can modify attributes, methods, code blocks and classes

(1) 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 Test{
    public int a;//Ordinary member variables and instance variables are stored in the object
    public static int count;//Class variables are also called static member variables 
    public final SIZE;//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
}
public class Main{
    public static void main(String[] args) {
        Test t1 = new Test();
        t1.a++;
        Test.count++;
        System.out.println(t1.a);
        System.out.println(Test.count);
        System.out.println("---------------");
        Test t2 = new Test();
        t2.a++;
        Test.count++;
        System.out.println(t2.a);
        System.out.println(Test.count);
   }
}

Compile and run the code, and the output is as follows:

1

1

---------------

1

2

Note: count is modified by static and shared by all classes. And it does not belong to the object. The access method is: class name Attributes

Memory resolution is as follows:

(2) modification method

If applied on any method static Keyword, this method is called static method
① Static methods belong to classes, not objects belonging to classes
② You can call static methods directly without creating an instance of the class
③ Static methods can access static data members and change their values
be careful:
(i) Static methods are instance independent , It's about classes Therefore, this leads to two situations: a. static methods cannot directly use non static data members or call non static methods ( Non static data members and methods are instance related) b this and super Two keywords cannot be used in a static context (this Is a reference to the current instance , super Is a reference to the parent instance of the current instance , also Is related to the current instance )
(ii) a method, whether or not to bring static, It all depends on the situation
(iii) whether main is a static method or not depends on our JVM
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);   
   }
}

Compile and run the code, and the output is as follows:

100

3, Encapsulation

1. What is encapsulation

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 doesn't 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 costs of class users, thus reducing the complexity

2.private implementation encapsulation

private/ public These two keywords represent " Access control "
(1) Be public Modified member variable or member method , Can be used directly by the caller of the class
(2) Be private Modified member variable or member method , cannot be used by the caller of the class( Class users don't need to know or pay attention to the private members of a class This allows class callers to use classes at a lower cost)
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.name = "Zhang San"// error
     person.show(); 
     } 
}
If the implementer of the class changes the name of the field , The caller of the class does not need to make any changes ( The caller of a class cannot access fields such as name and age at all however 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 rarely happens General class design requires that the public method provided by the class should be relatively stable and should not change frequently This is especially true for classes in some basic libraries Every time the interface is changed, the compatibility problem should be carefully considered

3.getter and setter methods

When we use private To decorate the field , you cannot use this field directly. At this time, if you need to obtain or modify this private attribute , You need to use getter / setter method
(1)getName mean getter method , Gets the value of this member
(2)setName mean setter method , Represents 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 indicates 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
class Person { 
    private String name;//Instance member variable
    private int age; 
  
    public void setName(String name){ 
    //name = name;// It cannot be written like this. At this time, all three names are the same name, because local variables take precedence
    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("xiaoxiao"); 
    String name = person.getName(); 
    System.out.println(name); 
    person.show(); 
}

Compile and run the code, and the output is as follows:

xiaoxiao

name: xiaoxiao age: 0

4, Construction method

1. The construction method is a special method, Use keywords new Automatically called when a new object is instantiated , Used to complete the initialization operation
2. Execution process of new: ① allocate memory space for the object; ② call the construction method of the object
3. Grammar rules:
(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)
4. Note:
(1) If no constructor is provided in the class, the compiler will generate a constructor without parameters by default
(2) If a construction method is defined in the class, the default parameterless construction will no longer be generated
(3) The constructor supports overloading . The rules are consistent with the overloading of ordinary methods
5.this keyword: this Represents the current object reference ( Note that it is not the current object ). Can help this to access the fields and methods of the object. Inside the constructor, we can use this keyword. The constructor is used to construct the object. The object has not been constructed yet, We use this. Does this still represent the current object? Of course not. This represents the reference of the current object
this can generally be used as follows:
(1)this.data calls the properties of the current object
(2)this.func() calls the method of the current object
(3) this() calls other construction methods of the current object
class Person { 
     private String name;//Instance member variable
     private int age; 
     private String sex; 
     
     public Person() { //The default constructor constructs the object. The public here cannot be modified to private. Once modified in this way, the object cannot be instantiated outside the class, but it can be instantiated inside the class
     this.name = "caocao"; 
     this.age = 10; 
     this.sex = "male"; 
     } 
 
     public Person(String name,int age,String sex) { //A constructor with three parameters constitutes an overload between two constructors
     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(); 
   } 
}

Compile and run the code, and the output is as follows:

name: caocao age: 10 sex: male
name: zhangfei age: 80 sex: male
class Person{ 
    private String name;

    public Person(){
       //this();//error calls other construction methods of the object, forming infinite recursion
       this("xiaoxiao");//Calling a constructor with one parameter must be placed on the first line
       System.out.println("Person()-->Construction method without parameters");
    }
    public Person(String name){
       this.name = name;
       System.out.println("Person(String)-->Construction method with one parameter");
    }
    public void show() { 
       System.out.println("name: "+name); 
   }
       
}
public class Test{
    public static void main(String[] args){
        Person person = new Person();
        person.show();
        System.out.println(person);
    }
}

Compile and run the code, and the output is as follows:

xiaoxiao

Person (string) -- > construction method with 1 parameter

Person() -- > constructor without parameters

5, Code block

1. The initialization methods of fields are: (1) local initialization, (2) initialization using construction methods, and (3) initialization using code blocks. The first two methods have been summarized earlier. Next, we introduce the third method, which uses code block initialization

2. According to the location and keywords defined by the code block, it can be divided into four types: local code block (ordinary code block), static code block, construction code block and synchronous code block

(1) Native 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); 
    } 
}

Compile and run the code, and the output is as follows:

x1 = 10

x2 = 100 

This usage is rare

(2) Construct code block

Building blocks: blocks of code defined in a class ( No modifier ) . Also known as: Instance code block . Construction code blocks are generally used to initialize instance member variables
Note: instance code blocks take precedence over constructor execution
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(); 
     } 
}

Compile and run the code, and the output is as follows:

I am instance init()!
I am Person init()!
name: bit age: 12 sex: man
(3) Static code block
use static Defined code block. Generally used to initialize static member properties
be careful: No matter how many objects are generated, the static code block will only be executed once and will be executed first. After the static code block is executed , The instance code block (construction block) is executed, and then the constructor is executed
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();//The static code block will not be executed
   } 
}

Compile and run the code, and the output is as follows:

I am static init()!

I am instance init()!

I am Person init()!
(4) Synchronous code block
It will be summarized in subsequent notes

6, Supplement

1.toString method:

(1) The toString method will be called automatically at println

(2) The operation of converting an object into a string is called serialization

(3) 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 toString method to implement our own version of conversion string method

(4) Shortcut key of toString method for IDEA to quickly generate Object: alt+f12(insert)

You don't need shortcut keys. Right click to find generate, then find toString(), and then click ok

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) { 
    Person person = new Person("caocao",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); 
    } 
}

Compile and run the code, and the output is as follows:

name : caocao age : 19
Person@1c168e5
We can take a look at the source code of println:

Override toString method:

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//@Override is called "Annotation" in Java. Here @ override means that the toString method implemented below is a method that overrides the parent class 
     public String toString() { 
         return "Person{" + 
                "name='" + name + '\'' + 
                ", age=" + age + 
                '}'; 
    } 
} 
public class Main { 
    public static void main(String[] args) { 
        Person person = new Person("caocao",19); 
        person.show(); 
        System.out.println(person); 
    } 
}

Compile and run the code, and the output is as follows:

name : caocao age : 19
Person{name='caocao', age=19}

 2. Anonymous object

(1) Objects that are not referenced are called anonymous objects

(2) Anonymous objects can only be used when creating objects

(3) 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
    } 
}

Compile and run the code, and the output is as follows:

name : caocao age : 19

Topics: Java Back-end JavaSE