Object oriented II (method, encapsulation, this, recursion, javaBean concept, static concept, singleton pattern)

Methods and packaging

Basic concepts of construction method

  • When the constructor name is exactly the same as the class name, there is no return value type, and void cannot be used.
class Class name{										class Person{
	Class name(parameter list ){									Person(){ // The Person method is the constructor of the Person class
		Construction method body;											
	}												}
}												}
  • A default constructor will be automatically created in each class. When no constructor is defined in a class, the compiler will automatically add a parameterless null constructor
    The constructor is called default / default constructor, such as Person() {}
class Person{
	Person(){  //This is a default constructor. It is generated by default in the class. Even if it is not generated, it will be automatically generated by the compiler.
	}
}
  • If a constructor occurs in a class, the compiler no longer provides any form of constructor.
class Person{
	Person(){  //Create construction method
		System.out.println("Custom construction method");
	}
}

Function of construction method

  • When the new keyword is used, the constructor will be automatically called to initialize the member variable when creating the object. The constructor can only be used during new, and others cannot be called.
public class Person {

    int first;
    int theSecond;

    Person(){//In new, it is executed to open up a space in the heap	
        System.out.println("Custom construction method");
    }

    Person(int i,int s){//
        first = i;
        theSecond = s;
        System.out.println("When the program is initialized, the initialization value is passed to the parameter i=" + first + ",j=" + theSecond);
    }
    public static void main(String[] args) {

    	Person person = new Person(); //Create a stack space and a heap space
        Person person1 = new Person(1,2);//Recreate a stack space, and heap space
        System.out.println("Check to see if there is any change after passing in the value,View first value:" + person1.first + "View the second value:" + person1.theSecond);

    }
}
Output as>>>
Custom construction method
 When the program is initialized, the initialization value is passed to the parameter i=1,j=2
 Check to see if there is any change after passing in the value,View first value: 1 view second value: 2

Concept of method overloading

  • If the method names are the same and the parameter lists are different, such methods form an overload relationship
public class Overload {

   void Overloads(){
        System.out.println("Before method overloading");
    }

    void Overloads(int i){
        System.out.println("Method overloaded");
    }

    public static void main(String[] args) {
        Overload overload = new Overload();
        overload.Overloads();
        overload.Overloads(1);
    }
}
output>>
Before method overloading
 Method overloaded

Embodiment of method overload

  • The main forms of method overloading are: different number of parameters, different types of parameters, different order of parameters, which is independent of the return value type and formal parameter variable name, but it is recommended that the return value type should be the same.
  • Judge whether methods can constitute the core of overloading: whether they can be distinguished when calling methods.
public class Overload {


    void Overloads() {

        System.out.println("Before method overloading");
    }

    void Overloads(int i) {
        System.out.println("Method overloaded,This is reflected in the different number of method parameters");
    }

    void Overloads(int i, double d) {
        System.out.println("Method overloaded,It reflects the different number of methods");
    }

    void Overloads(int i, int j) {
        System.out.println("Method overloaded,This is reflected in the same number and different types of method parameters");
    }

    void Overloads(double d, int i) {
        System.out.println("Method overloaded,This is reflected in that the number of method parameters is the same, the types are the same as those above, and the order is different, but there cannot be the same types in the formal parameter list");
    }

//    void Overloads(double a,int c){
//        System.out.println("when an error is reported, method refactoring mainly focuses on the parameter type rather than the variable name of the parameter");
//    }

//    int Overloads(double a, int c) {
//        System.out.println("when an error is reported, the method reconstruction mainly focuses on the parameter type rather than the variable name of the parameter, and has nothing to do with the return value type");
//    }

    public static void main(String[] args) {
        Overload overload = new Overload();
        overload.Overloads();
        overload.Overloads(1);
        overload.Overloads(1, 1.2);
        overload.Overloads(1, 1);
        overload.Overloads(1.2, 1);
        System.out.println("When an error is reported, method refactoring mainly focuses on the parameter type rather than the variable name of the parameter");
        System.out.println("When an error is reported, method refactoring mainly focuses on the parameter type rather than the variable name of the parameter, and has nothing to do with the return value type");

    }
}

output>>>
Before method overloading
 Method overloaded,This is reflected in the different number of method parameters
 Method overloaded,It reflects the different number of methods
 Method overloaded,This is reflected in the same number and different types of method parameters
 Method overloaded,This is reflected in that the number of method parameters is the same, the types are the same as those above, and the order is different, but there cannot be the same types in the formal parameter list
 When an error is reported, method refactoring mainly focuses on the parameter type rather than the variable name of the parameter
 When an error is reported, method refactoring mainly focuses on the parameter type rather than the variable name of the parameter, and has nothing to do with the return value type

Significance of method overloading

  • The practical significance of method overloading is that the caller only needs to remember a method name to call different versions to achieve different functions.

this basic concept

  • The use of this keyword in the construction method represents the object currently being constructed.
  • Use the this keyword in the member method to represent the object currently being called.
  • this keyword is essentially a reference variable of the current type.
public class ThisUse {

    //Construction method
    ThisUse(){
        System.out.println("Use in construction methods this =" + this);
    }
    //Member method
    void show(){
        System.out.println("Use in member methods this = " + this);
    }

    public static void main(String[] args) {
        //Declare that a reference to the ThisUse type points to an object of that type
        ThisUse thisUse = new ThisUse();
        //Call show to display this
        thisUse.show();
        System.out.println("main In the method: thisUse = "+ thisUse);
    }
}
output>>>
Use in construction methods this =ThisUse@1540e19d
 Use in member methods this = ThisUse@1540e19d
main In the method: thisUse = ThisUse@1540e19d

You can see the output this The value of is the same,this Refers to the address of the reference space.
  • In a class, you do not need to call a member variable through the class name. Member variable name, but directly use the member variable name. The reason is that java has added this. Member variable name by default
	int s;
	void show(){
		System.out.println("When you use member variables directly within a method, you do not need to pass the class name.The member variable name is because java Automatically added to the member variable name this." );
		System.out.println("this.s="  + this.s + ",s = " + s);
	}
Output as>>>
When you use member variables directly within a method, you do not need to pass the class name.The member variable name is because java Automatically added to the member variable name'this.'
this.s=0,s = 0

How this works

  • When accessing member variables in construction methods and member methods, the compiler will prefix this. And this. Is equivalent to "my" in Chinese. When different objects call the same method, the this keyword is different due to different objects calling the method, so the results of this. Access will be different.
  • When the local variable name is the same as the member variable name, the local variable will be used preferentially in the method body (proximity principle). If you want to use the member variable, you need to prefix the member variable with this. To make it clear that the variable is a member variable, otherwise the variable in the formal parameter list on the method will be called.
	public class ThisUse {

    String name;  //full name
    int age;    //Age

	//Proximity principle
    void show(String name, int age) {
        name = name;
        age = age;
        System.out.println("name=" + name + "gae = " + age);
    }
    //Declare the called variable.
    void show(int age,String name) {
        this.name = name;
        this.age = age;
        System.out.println("name=" + name + "gae = " + age);
    }


    public static void main(String[] args) {
        //Declare that a reference to the ThisUse type points to an object of that type
        ThisUse thisUse = new ThisUse();

        thisUse.show("Zhang San", 19);
        System.out.println("In class name Is it assigned name  = " + thisUse.name);
        System.out.println("In class name Is it assigned age = " + thisUse.age);

        thisUse.show(19,"Li Si");
        System.out.println("In class name Is it assigned name  = " + thisUse.name);
        System.out.println("In class name Is it assigned age = " + thisUse.age);
    }
}
output>>>
name=Zhang San gae = 19
 In class name Is it assigned name  = null
 In class name Is it assigned age = 0
name=Li Si gae = 19
 In class name Is it assigned name  = Li Si
 In class name Is it assigned age = 19


According to the results shown in the above code, if you use the same name, you need to declare the variable you want to call with this.

  • This keyword can not only call member variables and member methods through this., but also be used as the return value of the method.
public class ThisUse {

    //Create a member method to obtain and return the type object of the class
    ThisUse thisUse() {
        return this;
    }

    public static void main(String[] args) {
        //Declare that a reference to the ThisUse type points to an object of that type
        ThisUse thisUse = new ThisUse();
        ThisUse thisUse1 = thisUse.thisUse();
        System.out.println("thisUse = " + thisUse);
        System.out.println("thisUse = " + thisUse1);

    }
}

output>>>
thisUse = ThisUse@1540e19d
thisUse = ThisUse@1540e19d
  • In the first line of the constructor, you can use this() to call other constructor methods in this class
public class ThisUse {

    String name; //Declare a member variable

	//By passing a value to this(), a parameterized construction method is used
    ThisUse(){
//        this("Li Si");
        System.out.println("Declare a parameterless constructor");
    }

    //Call the parameterless constructor directly through this()
    ThisUse(String name){
        this();
        System.out.println("Declare a parameterized constructor");
        this.name = name;
    }
	//The use of this() cannot exceed the number of constructors - 1
    ThisUse(int a){
        this("zhang");
        System.out.println("Declare a parameterized constructor");
        this.name = name;
    }

    void show(){
        System.out.println("Print Name:" + name);
    }
    public static void main(String[] args) {
        System.out.println("test this()Effect of");
        ThisUse thisUse = new ThisUse();
        thisUse.show();

        System.out.println("--------------------------");
        new ThisUse("Wang Wu");
        thisUse.show();
    }
}

be careful

  • The reference type variable acts on the storage address and can be set to null, indicating that no object is executed.
  • However, if the reference type variable is set to null, the memory address information is null. When calling the member method, an error will be reported and a null pointer exception will be reported: NullPointerException

Basic concepts of recursion

  • The concept of recursion starts from the initial value and is calculated in the same way until the end.
  • The essence of recursion is to call the current method itself directly or indirectly inside the method body.
/**
 * Factoring
 */

public class FactorialTest {

    //Factoring
    int show(int s){
        //Recursion starts from the initial value and uses the same operation method to calculate until the end.
        System.out.println("It is calculated by recursion");
        int num=1;
        for(int i=1;i<=s;i++){
            num *= i;
        }
        return num;
    }

    /**
     *Calculation method: the factorial of 5 is 5! To represent
     * So 5= 5 * 4!
     *      4! = 4 * 3!
     *      3! = 3 * 2!
     *      2! =  2 * 1!
     *      1! = 1
     */
    int show1(int s){
        System.out.println("It is calculated recursively");
        //Because 1 does not need factorial calculation= 1. This judgment is an exit condition
        if(s == 1) return 1;
        return s*show(s-1);//When the exit condition is not established, continue to call its own member method, but when the exit condition is established, the value will be returned from bottom to top,
       	/**
         * Analysis: first judge whether s is equal to 1. If not, continue to run downward
         * show(5) ==> 5 * show(5-1)
         * ==> 4 * show(4-1)
         * ==> 3 * show(3-1)
         * ==> 2 * show(2-1)
         * ==> 1 Exit the self call and return the previously accumulated calculations.
         * When the subtracted value is 1, you can judge. return to exit the method.
         */
    }

    public static void  main(String[] args){
        FactorialTest test = new FactorialTest();
        int show = test.show(5);
        System.out.println("The output multiplication value obtained by recursion is:" + show);
        int show1 = test.show(5);
        System.out.println("The output multiplication value obtained by recursion is:" + show1);
    }
}
output>>>
It is calculated by recursion
 The multiplier value obtained by recursion is 120
 It is calculated by recursion
 The output multiplication value obtained by recursion is: 120

Recursive considerations

  • The use of recursion is to determine the regularity and exit conditions. It is like a for loop. When it reaches a point, it is necessary to set the end statement.
  • Using recursion is to simplify the problem rather than complicate it.
  • When recursion affects the performance of program execution, recursive replacement should be used.
public class FactorialTest {
	 //Find the sequence of Fisher numbers by recursion
    int show2(int s){
        if(s == 1 || s ==2){
            return 1;
        }
        return show2(s-1) + show2(s-2);//Because there are two method calls to be sealed, and then they continue to multiply, the operation efficiency is reduced, so it is not suitable to use recursion.
    }
	
	 public static void  main(String[] args){
        FactorialTest test = new FactorialTest();
        test.show2(50);
        System.out.println(50);

    }
}
Running time too long

The running time is too long. Although the results can be processed, recursion is not recommended.

Object oriented encapsulation

  • In general, you can assign some legal but unreasonable values to member variables in the test class. There will be no error or prompt in either the compilation stage or the running stage. At this time, it is inconsistent with real life
  • In order to avoid the above errors, member variables need to be sealed and packaged to hide the details of member variables and ensure the rationality of member variable values. This mechanism is called encapsulation

Implement packaging process

  • Privatize member variables and modify them with the private keyword.
  • Provide public get and set methods, and judge the reasonable value in the method body.
  • In the construction method, we call the set method to determine the reasonable value.

Encapsulation class

public class Package {
    //Privatize member variables through private, so that they can only be called inside the method
    private int id;
    private String name;

    Package(){}

    //In the public construction method, we call the set method to judge the reasonable value.
    Package(int id,String name){
        setName(name);
        setId(id);
    }

    //The member methods that provide get and set are public calls
    //Use this to point to variables so that they will only call member variables in the method
    public void setId(int id) {
        if(id>0){
            this.id = id;
        }else{
            System.out.println("Student number input error");
        }

    }

    public int getId() {
        if (this.id == 0 ){
            System.out.println("Re input before input / output error");
        }
        return id;
    }

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

    public String getName() {
        return name;
    }
    //Those without any modifiers are called default access permissions. The level is between private and public
    void show() {
        System.out.println("I am" + getName() + ",Student number:" + getId());
    }
}

Test class

public class PackageTest {
    public static void main(String[] args) {
        //No parameter is used and no value is transferred
        Package p = new Package();
        p.setId(-10000);
        p.setName("Zhang San");
        p.show();

        System.out.println("-------------------");
        
        //Use parameters to transfer values
        Package p1 = new Package(10000, "Li Si");
        p1.show();
    }
}

Topic test

import java.util.Scanner;

/**
 * Prompt the user to enter the number of students in the class and the information of each student. The student information includes:
 * Number and name, and finally print them out respectively.
 * Prompt: Student[] arr = new Student[num]
 */

public class PackageTest2 {
    public static void main(String[] args) {

        //Prompt user for input
        System.out.println("Please enter the number of students:");
        Scanner sc = new Scanner(System.in);
        int quantity = sc.nextInt();
        //Prepare an array according to the number of students
        //Each element in the array is of type int, which means that each element in the array can be regarded as an int variable and initialized with an integer, arr[0]=10;
        //Package [] declares a one-dimensional array with the length of quantity and the element type of package
        //Each element in the array is of Package type, that is, each element in the array can be regarded as a variable of Package type, arr[0]= new Package();
        Package[] arr = new Package[quantity];

        //Prompt the user for input and record it in a one-dimensional array
        for (int i = 0;i<quantity;i++){
            System.out.println("Please enter page"+(i+1)+"Student information(Student number+name): ");
            arr[i] = new Package(sc.nextInt(),sc.next());
        }

        System.out.println("---------------------------");
        //Print all student information
        System.out.println("The information of all students in this class is: ");
        for (int i=0;i<quantity;i++){
            arr[i].show();
        }

    }
}

Concept of JavaBean

  • JavaBean is a reusable component written in Java language. Other Java classes can discover and manipulate the properties of these JavaBeans through reflection mechanism.
  • JavaBean s are essentially Java classes that meet the following standards:
    • Class is public
    • There is a public constructor without parameters
    • There are properties and corresponding get and set methods

Static static concept

  • Use the static keyword to modify the member variable to indicate the meaning of static. At this time, the member variable is promoted from the object level to the class level, that is, there is only one copy of the whole class and shared by all objects. The member variable is ready with the loading of the class, regardless of whether to create an object.
  • Members modified by the static keyword can be accessed by referencing. But the class name. Is recommended.
	public static String country;//Declare static variables
  • In non static methods, you can call static members or non static members (members: member variables or member methods, and static members are shared by all objects)
public class Static {
    public String name;
    public int age;
    public static String country = "China";


    public void Country(){
		 System.out.println("Non static member method calls non static member variable:"+ name);
        System.out.println("Non static member methods call static variables:"+ country);//Static members are shared by all objects, and the this keyword can be omitted
    }

    public static void main(String[] args) {
        Static aStatic = new Static();
        aStatic.Country();
    }
}
  • In a static member method, only static members can be accessed, and non static members cannot be accessed. (member: member variable + member method, because the object may not be created at this time)
public class Static {
    public String name;
    public int age;
    public static String country = "China";


    public void Country(){
        System.out.println("Non static member method calls member variables:"+name);
        System.out.println("Non static member methods call static variables:"+country);
    }

    public static void Country1(){//There is no this call mode in static methods
//        System.out.println("static member method calls member variable" + name)// An error is reported. Non static variables cannot be referenced from a static context
        System.out.println("Non static member methods call static variables:"+ country);
    }

    public static void main(String[] args) {
        Static aStatic = new Static();
        aStatic.Country();
        Static.Country1();
    }
}

  • In future development, only the content belonging to the class level and shared by all objects can be modified with the static keyword.

Building blocks and static code blocks

  • Construction block: a code block directly enclosed by {} in the class body; The building block is executed once for each object created.
{	//The construction block is executed by the construction method first. In the construction block, the preparations before the construction method can be executed first.
	System.out.println("Execution building block");
}

output==>
Execution building block
  • Static code block: a construction block decorated with the static keyword; Static code blocks are executed once as the class loads
//Use static code blocks when you need to do some preparatory work to load classes before the code block
static{//Static code blocks are executed before building blocks, but only once as the class loads
	System.out.println("Execute static code block");
}

Singleton mode

  • In some special cases, when a class provides only one object externally, such a class is called a singleton class, and the process and idea of designing a singleton are called a singleton design pattern.

Singleton class

/**
 * Programming the encapsulation of Singleton class
 */

public class Singleton {

    //2. Declare that the reference of this class type points to the object of this class type, and use the private static keyword to modify it together
//    private static Singleton sin = new Singleton(); // Starving Han style will open up space when it is created
    private static Singleton sin = null; //Lazy, created only when called

    //1. The privatization construction method is modified with the private keyword
    private Singleton(){

    }

    //3. Provide a public get method to return the object and use public static
    public static Singleton getInstance(){
//        return sin;// Hungry Han style
        if (null == sin){//Lazy style
            sin = new Singleton();
        }
        return sin;
    }
}


Test class

/**
 * The Singleton class is programmed to test the Singleton class. It is required to be available in the main method
 * To and can only get one object of this class
 */
public class SingletonTest {
    public static void main(String[] args){

        Singleton  getInstance = Singleton.getInstance();
        Singleton  getInstance2 = Singleton.getInstance();
        System.out.println(getInstance == getInstance2);
    }
}
output>>true
  • Singleton process
  1. The privatization construction method is modified with the private keyword.
  2. Declare that the reference of this class type points to the object of this class type, and use the private static keyword to modify it.
  3. Provide a public get method, which is responsible for returning the object, and use the public static keyword to modify it.

Tags: Java Web Development Linux

Posted on Tue, 23 Nov 2021 04:12:02 -0500 by brodwilkinson