Xiao Yang's notes on learning Java 11

Posted by adt2007 on Sun, 05 Dec 2021 09:10:27 +0100

1, Construction method
1. Definition
The purpose of the constructor is to initialize the data in the object.
2. Format:
1) . the method name is the same as the class name
2) . there is no return value type, not even void
3) . there is no specific return value
3. Examples

class Student {
        private String name;
        private int age;
    Student(){
        System.out.println("This is a parameterless construction method");
    }

public void setName(String name){       //getXxx() and setXxx() methods
    this.name = name;
}

public String getName(){
    return name;
}

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

public int getAge(){
    return age;
}

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

}

public class StructureDemo1 {
    public static void main(String[] args) {
        Student s = new Student();      //create object
        //s.show();
    }
}
****The above code only new An object, and then run it to output"This is a parameterless construction method"****
****At this point, it means that a construction method will be automatically run when creating an object****
****When there is no such method in the code, Java It will create a null method without parameters and call it when constructing the object****

4. Thinking:
Before learning the construction method, we also came out of the new object. Now we know that we always call a parameterless construction method internally, but what
We don't have a constructor in class, so the question is where does the constructor we've been using come from?
be careful:
1) If we do not give a construction method, the JVM will automatically provide a parameterless construction method to us.
2) If we give the construction method, the JVM will no longer provide the default parameterless construction method.
If we do not give a parameterless construction method, but give other parameterless construction methods, the JVM will no longer provide the default parameterless construction method
As long as we give the construction method, whether with or without parameters, the JVM will never provide the construction method without parameters
3) , constructors can also be overloaded in the same class. (the method name is the same, the parameter list is different, and it has nothing to do with the return value)
5. Function of construction method:

​ You can assign values to the object's member variables when you create the object
​ There are two ways to assign values to member variables of objects:
​ 1) Use the public setXxx() method provided by the class to assign values to member variables
​ 2) . assign a value to a private member variable using a construction method with parameters,
​ Note that when the variable name of the formal parameter is the same as that of the member variable, it needs to be used together with the this keyword

6. Example of construction method

 class Structure {
        private String name;
        private int age;

    Structure() {
        System.out.println("This is our own nonparametric construction method");
    }

    Structure(String name) {
        System.out.println("This is our own tape name Parametric construction method with parameters");
        this.name = name;
    }

    Structure(int age){
        System.out.println("This is our own tape age Parametric construction method with parameters");
        this.age = age;
    }

    Structure(String name,int age){
        System.out.println("This is our own construction method with parameters with all member variables");
        this.name = name;
        this.age = age;
    }

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

}

public class StructureDemo2 {
    public static void main(String[] args) {
        Structure s1 = new Structure();
        System.out.println(s1);
    ****Here we will output: This is our own parameter free construction method, and s1 Address value for****
    ********com.shujia.yhl.day12.Structure@1540e19d****
        System.out.println("=======================");

        //Create a second object
        Structure s2 = new Structure("Wu Xie");
        s2.show(); //Output Wu Xie, 0
        System.out.println("=======================");

        //Create a third object
        Structure s3 = new Structure(17);
        s3.show();//Output null,17
        System.out.println("=======================");

        //Create a fourth object
        Structure s4 = new Structure("Zhang Qiling",18);
        s4.show();//Output Zhang Qiling, 18

    }
}

2, Class improvement
1. Class composition: member variables, member methods
2. Today I learned a new member: construction method
3. Improve the class we wrote earlier:
Member variable
Construction method
Member method:
According to whether there is a return value:
1) , member method with no return value
2) Member method with return value
According to whether there are parameters:
1) , parameterless member method
2) , member methods with parameters
4. Example 1

class Student2 {
            private String name;
            private int age;

        Student2() {        //Nonparametric construction method
        }

        Student2(String name, int age) {        //Construction method of parameters containing all member variables
            this.name = name;
            this.age = age;
        }

        public void setName(String name) {       //Public getXxx() method and setXxx() method
            this.name = name;
        }

        public String getName() {
            return name;
        }

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

        public int getAge() {
            return age;
        }
        
        public void printHello() {          //Member method with no parameters and no return value
            System.out.println("HelloWorld");
        }

        public String getTianQi() {         //Member method with no parameter and return value
            return "a sunny day";
        }

        public void sum(int a, int b) {     //Member method with parameter and no return value
            System.out.println(a + b);
        }

        public String concat(String s1, String s2) {         //Member method with parameter and return value
            return s1 + s2;
        }

        public void show() {
           System.out.println("full name:" + name + ",Age:" + age);      //Define a method to output all member variables
        }
    }

    public class StudentDemo {
        public static void main(String[] args) {
            
            Student2 s1 = new Student2();       //Create an object using a parameterless construction method
            s1.show();                          //Call a member method with no parameters and no return value
            s1.printHello();                    //Call a member method with no parameter and return value
            String tianqi = s1.getTianQi();
            System.out.println(tianqi);          //Call a member method with parameters and return values
            String s = s1.concat("Third uncle of Southern Sect","yyds");
            System.out.println(s);
            s1.sum(12,45);                      //Calling a member method with parameters and no return value

            Student2 s2 = new Student2("Arlene ",26);    //Create objects using a construction method with parameters
            s2.show();
        }
    }

5. Example 2
Standard class code version 3.0, a standard mobile phone class
analysis:
mobile phone:
Attributes: brand, color, price
Behavior: calling, texting, learning
Class:
Member variables: brand,color,price (decorated with private)
Construction method: nonparametric construction method and parametric construction method
Member methods: setXxx() and getXxx() methods
show(): output all member variables

public class Phone {
    private String brand;        //Define member variables
    private String color;
    private int price;

    Phone() {                   //Define construction method

    }

    Phone(String brand, String color, int price) {
        this.brand = brand;
        this.color = color;
        this.price = price;
    }

    public void setBrand(String brand) {        //Define common setXxx() and getXxx()
        this.brand = brand;
    }

    public String getBrand() {
        return brand;
    }

    public void setColor(String color) {        this.color = color;
    }

    public String getColor() {
        return color;
    }

    public void setPrice(int price) {
        this.price = price;
    }

    public int getPrice() {
        return price;
    }

    public void show() {                 //Define a method that can output all member variables
        System.out.println("Brand:" + brand + ",Color:" + color + ",Price:" + price);
    }
}

Mobile phone test class:
The second method is most commonly used in development. Single use is always more flexible than mixed use

public class PhoneDemo {
    public static void main(String[] args) {
        System.out.println("=======Create an object using a parameterless construction method and use setXxx()Assign values to member variables=======");
        Phone p1 = new Phone();
        System.out.println("Before assignment:");
        p1.show();
        p1.setBrand("Huawei");
        p1.setColor("black");
        p1.setPrice(4999);
        System.out.println("After assignment:");
        p1.show();
        System.out.println("================================================");
        System.out.println("=======Create an object using a construction method with parameters, and use getXxx()Get member variable=======");
        Phone p2 = new Phone("Smartisan Mobilephone","white",8888);
        String brand = p2.getBrand();
        String color = p2.getColor();
        int price = p2.getPrice();
        System.out.println("brand["+brand+"]\t colour["+color+"]\t Price["+price+"]");
    }
}

3, The process of creating objects by parameterless construction method
The procedure of calling a parameterless constructor to create an object.
Phone p = new phone
1. Load the compiled class file into the method area in memory
2. Load the main method into stack memory
3. Make room for Phone p in stack memory
4. Open up space in heap memory and give system default values to member variables
5. Assign the address value of the object in heap memory to the reference variable in the stack

4, The process of creating objects with parametric construction methods

class Student {
        private String name = "Hu Bayi";
        private int age = 18;

    	student (String name, int age){
        	this.name = name;
        	this.age = age;
    	}
	}

	class StudentDemo {
    	public static void main(String[] args){
   	 student s = new Student("Zhang Kaixuan",18);
    	}
	}

​ 1. Load the compiled bytecode file into the method area
​ 2. Load the main method into the stack for execution
​ 3. Open up memory space in the stack for the student variable s
​ 4. Open up memory space for student objects in heap memory
​ 5. Assign the system default value to the member variable, nu11, 0
​ 6. Initialization assignment of display to member variables, "Hu Bayi", 18
​ 7. Initializing and assigning values to member variables through construction methods, "Zhang Kaixuan", 17
​ 8. Assign the spatial memory address of the student object in the heap memory to the variable s in the stack, and the student variable s points to the student object in the heap memory

5, Packaging example
Title: define a class Demo, which defines a method for calculating the sum of two data, and defines a Test to Test.
The first way:

class Demo { 
        public int sum() {
            int a = 11;
            int b = 22;
            int c = a + b;
            return c;
        }
    }

public class Test1 {
    public static void main(String[] args) {
        Demo d = new Demo();        //create object
        int sum = d.sum();

    }
}

​ In the first way, the requirements of our topic are realized
​ But it's not good, because the value of addition is fixed, so it's not good
​ Improvement: two values can be passed in later

The second way:

class Demo { 
        public int sum(int x, int y) {
        return x + y;
        }
    }

public class Test1 {
    public static void main(String[] args) {
        Demo d = new Demo();        //create object
        int sum = d.sum(65,70);
        System.out.println(sum);
    }
}

​ Compared with the first method, the second method can manually pass in parameters
​ However, the implementation process does not use the knowledge of object-oriented encapsulation. We can try to define two parameters as member variables

The third way:

class Demo {
    private int a;
    private int b;

    public int sum(int a,int b){
        this.a = a;
        this.b = b;
        return (this.a+this.b);
    }
}

public class Test1 {
    public static void main(String[] args) {
        Demo d = new Demo();        //create object
        int sum = d.sum(65,70);
        System.out.println(sum);
    }
}

Summary:
Question: which way to achieve the optimal solution of the problem?
In fact, when should we consider using object-oriented thinking when facing business problems,
Or in other words, under what circumstances do we define parameters in our problem as member variables?
Answer: only when the parameters in our topic form the relationship between attributes and behaviors of this class can they be defined as member variables
Because classes are used to describe things in the real world, member variables are used to describe classes
So, the second way to solve this problem is the optimal solution.

additional
1. Shortcut key
alt+Insert can quickly call up set and get methods
2. Guide Package
The import statement of the import package needs to be placed at the front of all the code

6, static keyword
1. static keyword
Define a person's class. The member variables include name, age and nationality. When instantiating the object, it is found that if many people have the same nationality,
For example, in China, each time it is created, such a variable space will be opened in the heap memory, which will cause a certain waste,
So is there any way to let all people of the same nationality share the value of one nationality?
If multiple objects have a common member variable, the value is the same
Java provides us with a keyword to deal with this situation. This keyword is called static
Member variables and member methods can be modified. When modifying member variables, multiple objects can share the value of a member variable,
Note: if you modify the nationality of any of these objects, the nationality of all will change.

class Person{
    private String name;        //full name
    private int age;            //Age
    private String nationality;   //nationality
    private static String nationality;
    public Person() {
    }

    public Person(String name, int age, String nationality) {
        this.name = name;
        this.age = age;
        this.nationality = nationality;
    }

    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    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 String getNationality() {
        return nationality;
    }

    public void setNationality(String nationality) {
        this.nationality = nationality;
    }

    public void show(){
        System.out.println("full name:"+name+",Age:"+age+",Nationality:"+nationality);
    }
}

public class PersonDemo {
public static void main(String[] args) {
    Person p1 = new Person("Hu Bayi",26,"China");   //Create first object
    p1.show();

    Person p2 = new Person("Wang Kaixuan,30);          //Create a second object
    p2.show();

    Person p3 = new Person("Yang Xueli",18);        //Create a third object
    p3.show();

    System.out.println("==========================================");   //If you change your nationality, all three will be changed
    p1.setNationality("U.S.A");
    p1.show();
    p2.show();
    p3.show();
    }
}

2. static features: it can modify member variables and member methods
1) . load as the class is loaded
Before running, the class file will be loaded into the method area, and the members decorated with static will be loaded with the loading of the class,
So members modified by static are stored in the method area. Recall the main method
2) , prior to object existence
3) Shared by all objects of the class
For example: all Chinese have the same nationality information
When to use the static keyword?
If a member variable is shared by all objects, it should be defined as static.
give an example:
Hello bike: (can be modified by static)
Own water cup: (can't be modified by static)
4) . statically decorated members can be called directly through the class name
Generally, when we develop in the future, we only need to see that there are static member variables or member methods in the class
In the future, all calls are called by class name, static member, and so on. It is recommended to use class name to call. This is also a specification.
Different members are distinguished by calling
Therefore, statically modified members are generally called class members, which are related to classes
4) . examples

class Demo2{   
        int a = 10;     //Define a non static member variable 
        static int b = 20;  //Define a static member variable
    }

public class StaticDemo1 {
    public static void main(String[] args) {
        Demo2 d1 = new Demo2();
        System.out.println(d1.a);
        //System.out.println(d1.b);
        System.out.println(Demo2.b);    //Same as the output of the previous sentence
    }
}

3. Static member access problem
1) static can modify member variables and member methods
2) . non static member methods:
1) Non static member variables are accessed
sure
2) Static member variables are accessed
sure
3) Access is a non static member method
sure
4) Static member methods are accessed
sure
Summary: non static member methods can access both static and non static members
Static member method:
1) Non static member variables are accessed
may not
2) Static member variables are accessed
sure
3) Access is a non static member method
may not
4) Static member methods are accessed
sure
Summary: static member methods can only access static members