Java grammar foundation (3)

classes and objects

  Object Oriented Language Overview

  java is an object-oriented language, what is an object-oriented language? To understand what an object-oriented language is, we need a relative understanding of procedural-oriented languages. In the introductory stage of java, we have told you about the classification of some languages, such as machine language, assembly language, which we call low-level language, c language, java, c++, etc. are all high-level languages. Among high-level languages, C language belongs to procedural language, and Java, C++, etc. are all object-oriented languages. Procedural language features: all statements are predicate-object phrases, because the cpu is the only unit that receives and processes commands. Both storing and manipulating data are done by the CPU. Go it alone, step by step. is a mapping of our mathematical logic. The characteristics of object-oriented language: the object is the unit that receives and processes data, and the objects perform their own duties, cooperate with each other, and have a higher degree of modularity. Clear division of labor and collaboration. It is a mapping of the logic of our life. Relatively speaking, object-oriented languages ​​are easy to maintain, high quality, efficient, and easy to expand; however, procedural languages ​​have higher execution efficiency. How to understand their characteristics: Give an example of cooking in our life. The three basic characteristics of object-oriented languages: encapsulation, inheritance, polymorphism. In the process of learning object-oriented languages, we need to figure out two conceptual classes and object classes: the definition (or abstraction) of a class of things with the same properties or behavior. It is a conceptual thing that cannot be seen or touched. Object: An instantiation of a class, a reification. It is a specific thing that exists objectively and conforms to the characteristics described by the class. How to understand these two concepts, such as "people", people are a class, which represents the abstraction of people. When you mention the concept of human, everyone will think of it, two arms and two legs, two eyes and one mouth, can talk, can eat, is a kind of animal with a high level of social speech. The concept stuck in my head. Then "Xiao Ming" is an object, Xiao Ming is a real object, no longer a conceptual thing, but a concept that can be seen and touched, and no longer stays in the mind

  Process-oriented object-oriented cooking and cooking process-oriented process: (You are the only dog ​​at home, so) Go to the market to buy vegetables, go home to wash vegetables, pick up vegetables, stir-fry vegetables, and serve them on the table. Object-oriented process: (You decide to hire housekeeping Nanny's home cooking service) Call the housekeeping company and apply for home cooking service. The housekeeping company informs the nanny "Cuihua" to receive this service Cuihua goes to the vegetable market to buy vegetables Cuihua takes the vegetables home to Cuihua for washing Vegetables, Taocai Cuihua

  To understand classes and objects: 1) From the logic of life: People are classes. "Xiao Ming" is the object. 2) Understand from the perspective of encapsulation: In c language, structure: is the encapsulation of data structure; in c language, function: is the encapsulation of the method of processing data. Class: It encapsulates data structures and data processing methods at the same time. 3) Understanding from the perspective of programming: Class: is a self-defined type; Object: is the variable generated by this type. 4) Officially defined class: an abstraction of objects with the same characteristics. Object: A representation of a class.

  class definition and usage

  If you want to create and use objects in java, you must first declare a class. A class is a blueprint. With a blueprint, the jvm knows how to create an object. There are two main sources of classes in java: 1. Sun has defined many classes and stored them in the jar package. We only need to import and use them. 2. Developers define classes and customize classes through the class keyword. The declaration format of a class in java: class class name { member variable; (defining the attributes of things) member functions; (also called methods, defining the behavior of things) } class: keyword, indicating that a class name is to be defined here: java identifier Character, in line with the big camel case nomenclature {}: the scope of the class member function: In fact, it is a variable defined inside the class, outside the member method. Conforms to the declaration specification for variables. Member function: conforms to the declaration specification of a function. After declaring a class, you need to create an object before you can call the member variables and methods of the object (we will talk about static classes and static methods later) We use the new keyword to create objects. Object creation format: new class name (); In order to use the object, we need to define a variable to receive the object: class name object name = new class name (); Access to object member variables is accessed through the. syntax to access the member variable format of the object: Object name. Member variable (get the value of the member variable) Object name. Member variable = value (member variable assignment) Member function call through. Syntax call member function format: Object name. Member function (); How to define a class yourself: 1 Determine what you describe, and separate common attributes and behaviors 2 Define the name of the class according to the class specification 3 Select the appropriate type to define member variables according to the accumulated attributes 4 Define the appropriate return value type and parameters according to the behavior of the class member function of

  For example, we declare a cat class to describe the cat class Cat { String name; int age; public void mew(){ System.out.println("Meow~"); } }

  object memory map

  

  Difference between member variable and local variable

  The difference between member variables and local variables: Member variables are defined outside the method and within the class. Local variables are defined within methods. The role of member variables is to describe the public properties of a class of things. The role of local variables is to provide a variable for internal use in the method. The life cycle exists as the object is created and disappears as the object disappears. A local variable exists when the corresponding method is called and the statement that creates the variable is executed. Once the local variable goes out of its own scope, it immediately disappears from the memory. A member variable with an initial value has a default initial value. Default initial value of data type int 0 float 0.0f double 0.0 boolean false char ' ' String (reference data type) null Local variables do not have default initial values ​​and must be initialized before they can be used.

  anonymous object

  Anonymous Object: An object that does not point to a variable of reference type is called an anonymous object. Points to note about anonymous objects: 1. We generally do not assign attribute values ​​to anonymous objects because they can never be obtained. 2. Two anonymous objects can never be the same object. Anonymous Object Benefits: Simplifies writing. Application scenarios of anonymous objects: 1. If an object needs to call a method once, and after calling this method, the object is no longer used, and anonymous objects can be used at this time. 2. A function can be called as an argument.

   //Student class class Student{ int num; //Student ID String name; //Name public void study(){ System.out.println("Study hard and prepare for being called Gao Shuai Fu in the future!"); } } class Demo4{ public static void main(String[] args) { //Create a student object//Student s = new Student(); //new Student().name = "Dog baby"; //Anonymous object/ /System.out.println(Student().name); //null System.out.println(new Student() == new Student()) ; // "==" is used to refer to type variables, the comparison is the memory address. Determine whether two objects are the same object requirements: Call the study method of Student. Student s = new Student(); s.study(); new Student().study(); } }

  package

  Encapsulation, that is, hiding the attributes and implementation details of objects, only exposing the interface to the outside world, and controlling the access level of reading and modifying attributes in the program; combining the abstracted data and behavior (or functions) to form an organic whole, also It is to organically combine the data with the source code for operating the data to form a "class", in which both data and functions are members of the class. Permission modifiers: Permission modifiers control the visible scope of variables. public : public. Publicly modified member variables or methods can be accessed directly by anyone. private : Private, privately modified member variables or methods can only be accessed directly in this class. The steps of protect default encapsulation: 1. Use private to modify the properties that need to be encapsulated. 2. Provide a public method to set or get the private member property. Public method naming convention: Method for setting value: set attribute name(); Method for obtaining value: get attribute name(); Example: member's sex attribute.

 

Constructor

  The role of the constructor

  Objects can be initialized using constructor functions. When the constructor is not used, we assign values ​​to each member variable, and we need to access each member variable through the . syntax and assign values ​​in turn. Using the constructor, we can initialize member variables directly when creating an object (new object). When we initialize the object, we can assign values ​​directly when declaring member variables, but in this case, the value of the member variables of each object created will be the same. So this way can not replace the constructor.

  For example, create a cat class Cat{ String color; String name; Cat(String c,String n){ color = c; name = n; } } void main(){ //If there is no constructor Cat tom = new Cat() ;//If a constructor with parameters is defined, an error will be reported here, because the compiler no longer automatically produces a parameterless constructor tom.name = "Tom"; tom.color = "Blue"; //If there is a constructor function, we can Cat tom = new Cat("Tom", "Blue"); }

  Constructor code writing format

  The code writing format of the constructor: Modifier function name (formal parameter) { function body... } Details that the constructor needs to pay attention to: 1 The constructor does not need to specify the return value type2 The constructor function name must be consistent with the class name3 The constructor is not called by us manually. The jvm virtual machine will actively call the constructor when the object is created. 4 If a class does not have a constructor written in the code, the java compiler will automatically add a no-argument structure to the class when compiling. Function 5 If a class has a constructor written in the code, the java compiler will no longer automatically add a parameterless constructor to the class during the compilation phase. 6 Constructors can exist in a class by overloading multiple constructors.

  If we do not manually write the constructor in the class, the java compiler will automatically add the constructor. How to verify this? Everyone should pay attention to the difference between the compilation phase and the running phase. The javac command is to compile the java source code file. In order to generate the class class file, the java command is to start the jvm virtual machine and run the class file. After the javac command compiles the class file, we can use the decompile tool to view the generated class file. The command to decompile the class file: javap -c -l -private class name Through decompilation, we can see if the compiler has created a constructor for the java class

  If we write a constructor with parameters by hand, the compiler will no longer generate a constructor without parameters. In this case, we pass new Cat(); and it will fail. Because when the object is created, the no-argument constructor cannot be found. If you want to not report an error, you can overload and provide both parameterized and parameterless constructors.

  Difference between constructor and normal function

  The difference between return value types: Constructors have no return value type, and ordinary functions have return value types. Even if the function has no return value, the return value type must be written as void. The difference between function names: The function name of the constructor must be consistent with the class name, and the function name of the ordinary function only needs to conform to the naming rules for identifiers. The difference in calling method: 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 ordinary functions. The difference in function: The function of the constructor is used to initialize an object. Ordinary functions are used to describe the public behavior of a class of things.

 

Building code blocks

  The role of constructing code blocks

  Using construction code blocks, you can perform uniform initialization operations on objects. Correspondingly, using the constructor, you can initialize the object. For example: ask everyone to define a mobile phone class, each time a mobile phone object is created, the mobile phone has its own production number and model name. All mobile phone objects are required to undergo a product test when they are created, and they can be sold without problems. Then the work of the test is called when each object is created.

  For example, create a cat class Cat{ String color; String name; Cat(String c,String n){ color = c; name = n; } } void main(){ //If there is no constructor Cat tom = new Cat() ;//If a constructor with parameters is defined, an error will be reported here, because the compiler no longer automatically produces a parameterless constructor tom.name = "Tom"; tom.color = "Blue"; //If there is a constructor function, we can Cat tom = new Cat("Tom", "Blue"); }

  Code writing format for constructing code blocks

  The writing format of the construction code block: {execute statement} Note: The construction code block must be written in the position of the member. Cannot be inside a method.

  Let's look at a piece of code: class Cat{ //constructor public Cat(){ num = 10; } //member variable int num = 1; //construction code block{ num = 5; } } void main(){ Cat c = new Cat(); println(c.num); } What is the final output? In the constructor, the variable num is used first, will an error be reported because there is no declaration? We can decompile the class file and find that it is possible. Points to note when constructing code blocks: 1. 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. 2. The initialization of member variables is actually performed in the constructor. 3. 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 middle code of the constructor is executed last. 4. The display initialization of member variables and the code for constructing the code block are executed in the order of the current code.

  Classification of building blocks of code

  Types of code blocks: 1. Construct code blocks. 2. Local code block. The local code block, written inside the method, is used to release the variables in it in advance, saving a little space. 3. Static code blocks will be explained in detail later 

 

this keyword

  this keyword

  The this keyword represents the current caller object of the function in which it is located. The function of using the this keyword: 1. If the local variable and the member variable have the same name, the this keyword can be used to distinguish the member variable from the local variable, and the local variable is accessed by default. 2 In the constructor, you can call another constructor to initialize the object.

  This keyword calls other constructors note

  1. The this keyword must be the first statement in the constructor. Otherwise, an error will be reported. 2. The this keyword cannot call each other in the constructor because it is an infinite loop.

  Notes on using this keyword

  1. When there are member variables and local variables of the same name, the local variables are accessed inside the method (java uses the "proximity principle" mechanism to access.) 2. If a variable is accessed in a method, the variable is accessed If there is only a member variable, the java compiler will add the this keyword in front of the variable.

 

static keyword

  static modifier static

  1 static can modify member variables 2 static can modify member functions

  static modifier member variable

  If there is data that needs to be shared by all objects, then static modification can be used. Access to static member variables: Mode 1: You can use the object to access. Format: object.variablename. Method 2: You can use the class name to access. Format: classname.variable name; Note: 1. Non-static member variables can only be accessed by using the object, not by the class name. 2. Never use static to modify member variables for the convenience of accessing data. Only use static modification when the data of member variables really need 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.

  Example: Define a membership class to count how many members are currently online.

  static modified member function

  Static modified method (static member method): Access mode: You can use the object to access. object.static functionname(); can be accessed using the class name. Class name. Static function name. The recommended use is to access static members directly by the class name. Matters needing attention for static functions: Static functions can be called by calling class names or objects, while non-static functions can only be called using objects. Static functions can directly access static members, but cannot directly access non-static members. Reason: A static function can be called directly by using the class name. At this time, the object may not exist yet, and the non-static member data exists with the existence of the object. Non-static functions are members that can directly access static and non-static members. Reason: non-static functions can only be called by objects. When the object exists, static data already exists, and non-static data also exists with the creation of the object. Static functions cannot have the this or super keyword. Reason: Because a static function can be called by using the class name, once the class name is used to call the object, there is no object, and the this keyword represents the caller object of a function, and a conflict occurs at this time. The life cycle of static data: static member variable data exists in preference to the object. Application scenarios of static modified functions If a function does not directly access non-static members, then static modification can be used. Generally, static functions of methods used in tool types cannot access non-static member static functions. As long as there is an object, they can also access non-static data. Just can't access it directly.

  static code block

  Static code block static{ execute code; } static code block, will be executed when the class is loaded into memory; and only executed once. Using static code blocks, you can initialize static member variables and call static methods.

  Difference between static variable and non-static variable

  1 Differences in function: The role of static member variables shares a data for all objects using non-static member variables to describe a class public property 2 Differences in quantity and storage location Static member variables exist in the memory of the method area, and only There is a non-static member variable that exists in the heap memory, and each object has a 3 life cycle difference: static exists with the loading of the class, disappears with the disappearance of the class file, non-static with the creation of the object While it exists, the garbage collection mechanism recycles and disappears.

 

Detailed explanation of main function

  Code: public static void main(Strings[] args){ System.out.println("Hello world!"): } public : public. Accessible under any circumstances. Make sure that the JVM can access the main method under any circumstances. JVM is also a program. It exists in the path of JDK->bin->client->jvm. If it is privately decorated, it cannot be accessed outside of the class JVM, and the main function cannot be called and executed. static: static. You can make the jvm call the main function without creating an object. static can be called directly by the class name, so that the jvm does not need to create an object. If you don't use static, it is not easy for jvm to create objects, because the class is written by the developer himself. If you don't use static, if you customize the constructor with parameters, there will be no default no-parameter constructor, and the jvm will advance in advance. If the type and number of parameters are not expected, the execution will fail. void: no return value. The main function is called by the jvm. If the main function returns, the program is executed. It is meaningless for the jvm to have such a return value. main: The function name. main is not a keyword, it is a function with a special name recognized by the jvm. The entire program has only one main function args (arguments): the parameters of the main function. You can pass parameters through the main function when executing the program. Main function pass parameters.

 

singleton design pattern

  Overview of Design Patterns

  A design pattern is a set of repeated, commonly known, categorized and catalogued summaries of code design experience. Design patterns are used to reusable code, make code easier to understand by others, and ensure code reliability. There is no doubt that design patterns are win-win for ourselves, others and systems; design patterns make coding truly engineering; design patterns are the cornerstone of software engineering, just like the structure of a building. Patterns are fixed steps to solve a problem.

  Overview of the Singleton Design Pattern

  The purpose of the singleton design pattern is to ensure that only one object exists in memory during the running process of the java program. The singleton pattern is very important, and this design pattern is used in many occasions in the programming process. Such as a music player, etc.

  Implementation of the singleton design pattern

  Hungry Chinese

  Code implementation steps: 1. Once the privatized constructor is privatized, objects cannot be created elsewhere. 2 Declare the reference type variable of this class, and use the variable to point to the object of this class private static Single s = new Single(); Note: a, use private modification to prevent access from outside the class b, use static modification, so that when the class is modified After loading into memory, space is allocated. And share. 3 Provide a public static method to obtain objects of this class. Public Static Single getInstance(){ return s; } The reason for using static modification is because the constructor is privatized, and objects cannot be created outside. And use public to provide a public interface to allow external access to the function to obtain the only simple interest object.

  class Single{ private Single(){ } private Static Single s = new Single(); public Static Single getInstance(){ return s; } }

  lazy

  The Hungry-style pattern has a downside: once the class is loaded into memory, an object is created. It is possible that the singleton object will not be used until the program runs to the end, thus wasting the object space. So we can use the lazy singleton pattern and create the object when the common method is called. Code implementation steps: 1. Private constructor 2. Declare the reference type member variables of this class, but do not create objects. private static Single s ; 3 Provide a public static method to obtain the object of this class, and judge whether the object of this class has been created before obtaining it. If it has been created, then return the object directly. If the object has not been created yet, create the object first, then return if the object has already been created.

  class Single{ private Single(){ } private Static Single s ; public Static Single getInstance(){ if (s == null) s = new Single(); return s; } }

  A Comparison of Implementations of the Singleton Design Pattern

  Both Hungry and Lazy can implement singleton mode Hungry creates a singleton object directly after the class is loaded. If you don't use it all the time, it will be a waste of space; Lazy will only create it when you call the shared method for the first time. object, relatively space-saving. At present, it is recommended that you use the hungry Chinese style, because the lazy style currently has thread safety problems. If multiple threads execute concurrently, the object may not be unique.

Guess you like

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