The eighth day of Java basic learning (constructor, construction code block, this keyword, static keyword)

1. Constructor

1. The role of the constructor: Initialize the corresponding object.

2. The format of the definition of the constructor:

修饰符  函数名(形式参数){
        函数体...
    }

3. Details to be paid attention to in the constructor:
① The constructor has no return value type.
② The function name of the constructor must be the same as the class name.
③ The constructor is not called manually by us, but when the corresponding object is created, the jvm will actively call the corresponding constructor.
④ If a class does not explicitly write a constructor, the java compiler will add a parameterless constructor for the class.
⑤ If a class has explicitly written a constructor, the java compiler will not add a parameterless constructor for the class.
⑥ Constructors can exist in a class in the form of function overloading.

4. Question: When an object is created, the jvm will call the corresponding construction method, so we have not learned the construction method before, so when the object is created before, will the jvm also call the construction method? If there is? Where does the constructor come from?
Answer: It will be called, and the java compiler will add it when compiling.

5. JDK provides a java development tool (javap.exe) for us to decompile.
The usage format of the javap decompilation tool: javap -c -l -private class name

6. Question: What is the permission modifier of the parameterless constructor added by the java compiler?
Answer: It is consistent with the permission modification of the class.

7. Differences between constructors and ordinary functions:
① Differences in return value types:
◆ Constructors have no return value type,
◆ Ordinary functions have return value types, even if the function has no return value, the return value type should also be written void.
② Differences in function names:
◆ The function name of the constructor must be consistent with the class name,
◆ The function name of the ordinary function only needs to conform to the naming rules of identifiers.
③ Differences in calling methods:
◆ The constructor is called by the jvm when the object is created.
◆ Ordinary functions are called by us using objects. An object can be an object of many times. Ordinary functions
④ Differences in function:
◆ The function of constructor is used to initialize an object.
◆ Ordinary functions are used to describe the public behavior of a class of things.

8. Requirements: Use java classes to describe a baby. In real life, there are two kinds of babies, one is born with a name (white household), and the other is a baby that has a name after birth (black household).

//婴儿类
class Baby{ 
    int id; //身份证 
    String  name;  //名字

    //构造函数
    public  Baby(int i , String n){
        id  = i;
        name = n;
        System.out.println("baby的属性初始化完毕!");
    }
    //无参的构造函数
    public Baby(){
        System.out.println("无参的构造函数被调用了..");
    }   

    //哭
    public void cry(){
        System.out.println(name+"哇哇哭...");
    }   
}
class Demo8.1{
    public static void main(String[] args){ 
        //创建一个baby对象
        Baby b1 = new Baby(110,"张三"); //婴儿诞生   白户
        System.out.println("编号:"+ b1.id +" 姓名:"+ b1.name);
        b1.cry();

        //黑户
        Baby b2 = new Baby();
        b2.id = 112;
        b2.name = "李四";
        System.out.println("编号:"+ b2.id +" 姓名:"+ b2.name);
    }
}

2. Construct code blocks

1. The role of constructing code blocks: uniform initialization of objects.

2. The role of the constructor: Initialize the corresponding object.

3. The format of the construction code block:

{
    构造代码块
}

Note: The curly braces that construct the code block must be in member position.

4. Types of code blocks
① Construct code blocks.
② Local code block. Braces are inside a method. Role: shorten the life cycle of local variables and save a little memory.
③ static code block static

class Baby{ 
    int id; //身份证 
    String  name;  //名字 

    //构造代码块...
    {
        System.out.println("构造代码块的代码执行了......");        
    }

    public  Baby(int i , String n){
        id  = i;
        name = n;
    }   
    public Baby(){
    }
    public void cry(){
        System.out.println(name+"哇哇哭...");
    }   
}
class Demo8.2{
    public static void main(String[] args){
        Baby b1 = new Baby(110,"狗娃");
        new Baby(112,"狗剩");
        new Baby();
    }
}

5. Matters needing attention when constructing code blocks:
① When the java compiler compiles a java source file, it will advance the declaration statement of member variables to the front end of a class.
② The initialization of member variables is actually performed in the constructor.
③ Once compiled by the java compiler, the code block that constructs the code block will be executed in the move constructor, which is executed before the constructor, and the code in the constructor is executed last.
④ The display initialization of member variables and the code for constructing the code block are executed according to the order of the current code.

class Demo8.3{  
    //构造函数
    public Demo5(){   //构造函数
        i = 3;  
    }       
    //构造代码块   //构造代码块的初始化
    {
        i = 2;
    }   
    int i = 1;   //成员变量的显初始化
    public static void main(String[] args){
        Demo5 d = new Demo5();
        System.out.println("i = "+d.i);
    }
}

Three, this keyword

Problem: When there are member variables and local variables with the same name, the local variables are accessed inside the method (java uses the mechanism of proximity principle to access).

1. This keyword: This keyword represents the caller object of the function to which it belongs.

2. The function of this keyword
① If there are member variables and local variables with the same name, the data of the local variables is accessed by default within the method, and the data of the member variables can be specified through the this keyword.
② In a constructor, you can call another constructor to initialize the object.

3. Matters needing attention when this keyword calls other constructors:
① When this keyword calls other constructors, the this keyword must be located in the first statement in the constructor.
② The this keyword cannot call each other in the constructor because it is an infinite loop.

4. Notes on this keyword
① When there are member variables and local variables with the same name, the local variables are accessed inside the method (java uses the "nearest principle" mechanism to access)
② If you access it in a method If a variable exists only as a member variable, the java compiler will add the this keyword in front of the variable.

class Animal{
    String name ;  //成员变量
    String color;
    public Animal(String n , String c){
        name = n;
        color = c;
    }   
    //this关键字代表了所属函数的调用者对象
    public void eat(){
        String name = "老鼠"; //局部变量
        System.out.println(this.name+"在吃..."); //需求:就要目前的name是成员变量的name.        
    }
}
class Demo8.4{
    public static void main(String[] args){
        Animal dog = new Animal("狗","白色"); 
        Animal cat = new Animal("猫","黑色");
        cat.eat();//猫在吃 
    }
}

5. Matters needing attention when
this keyword calls other constructors ① When this keyword calls other constructors, the this keyword must be located in the first statement in the constructor.
② The this keyword cannot call each other in the constructor because it is an infinite loop.

class Student{
    int id;  //学号
    String name;  //名字
    //目前情况:存在同名的成员变量与局部变量,在方法内部默认是使用局部变量的
    public Student(int id,String name){ //一个函数的形式参数也是属于局部变量
        this(name); //调用了本类的一个参数的构造方法
        //this(); //调用了本类无参的构造方法。
        this.id = id; //局部变量的id给成员变量的id赋值
        System.out.println("两个参数的构造方法被调用了...");
    }   
    public Student(){
        System.out.println("无参的构造方法被调用了...");
    }
    public Student(String name){
        this.name = name;
        System.out.println("一个参数的构造方法被调用了...");
    }
}
class Demo8.5{
    public static void main(String[] args){
        Student s1 = new Student(110,"张三");
        System.out.println("编号:"+ s1.id +" 名字:" + s1.name);

        Student s2 = new Student("李四");
        System.out.println("名字:" + s2.name);
    }
}

6. Requirements: Use java to define a human being with three attributes: id, name and age, and a method for comparing ages.
Requirements: The constructor must be written, and the constructor must also use the this keyword.

class Person{       
    int id; //编号
    String name; //姓名  
    int age;  //年龄
    //构造函数
    public Person(int id,String name ,int age){
        this.id  = id;
        this.name = name;
        this.age = age;
    }
    //比较年龄的方法
    public void compareAge(Person p2){
        if(this.age>p2.age){
            System.out.println(this.name+"大!");
        }else if(this.age<p2.age){
            System.out.println(p2.name+"大!");
        }else{
            System.out.println("同龄");
        }
    }
}
class Demo8.6{
    public static void main(String[] args){
        Person p1 = new Person(110,"张三",17);
        Person p2 = new Person(119,"李四",9);
        p1.compareAge(p2);
    }
}

Fourth, the static keyword

1. The current problems: All the students are Chinese. If there are n students, there will be n copies of Chinese data stored in the memory, which will waste memory.
Current solution: Move the data of "China" to the data sharing area, and share this data for all Student objects to use.
Question 2: How can this data be moved to the data sharing area for sharing?
Solution: Just decorate the data with static.

2. Only one copy of static member variables will be maintained in the data sharing area, while one copy of the data of non-static member variables will be maintained in each object.

class Student{
    String name;    
    //使用了static修饰country,那么这时候country就是一个共享的数据。
    static  String  country  = "中国";
    //构造函数
    public Student(String name){
        this.name = name;
    }
}
class Demo8.7{
    public static void main(String[] args){
        Student s1 = new Student("张三");
        Student s2 = new Student("陈七");
        s1.country = "其他";
        System.out.println("姓名:"+s1.name+" 国籍:"+ s1.country);//其他  
        System.out.println("姓名:"+s2.name+" 国籍:"+ s2.country);//其他
    }
}

3. Static can modify member variables: If there is data that needs to be shared with all objects, then static modification can be used.

4. Access
mode 1: You can use the object to access. Format: object.variable name
Mode 2: You can use the class name to access. Format: classname.variablename

5. Note
① Non-static member variables can only be accessed using the object, not the class name.
② Never use static to modify member variables for the convenience of accessing data. Only use static modification when the data of member variables really needs to be shared.
③ Application scenarios of static modification member variables: If a data needs to be shared by all objects, static modification can be used at this time.

6, static can modify member functions

class Student{
    String name;  //非静态成员变量 
    static  String  country  = "中国";      //静态的成员变量 
    public Student(String name){
        this.name = name;
    }
}
class Demo8.8{
    public static void main(String[] args){
        System.out.println("国籍:"+ Student.country);
    }
}

7. Requirements: Count how many times a class is used to create objects, and the class displays the number of times it was created.

class Emp{  
    static int count = 0;//计数器
    String name;    
    //构造代码块
    {
        count++;
    }
    public Emp(String name){
        this.name = name;
    }
    public Emp(){  //每创建一个对象的时候都会执行这里的代码        
    }   
    public void showCount(){
        System.out.println("创建了"+ count+"个对象");
    }
}
class Demo8.9{
    public static void main(String[] args){
        Emp e1 = new Emp();
        Emp e2 = new Emp();
        Emp e3 = new Emp();
        e3.showCount();
    }
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325946930&siteId=291194637