Learn the three main lines of object-oriented
1. Java classes and class members
Attributes, methods, constructors, code blocks, internal classes;
2. Three characteristics of object oriented
Encapsulation, inheritance, polymorphism, (abstraction);
3. Abstract classes, interfaces, and other keywords
this, super, static, final, abstract, interface, package, import, etc
1, Process oriented and object oriented
1.1 what is programming thought
Thought is a Chinese vocabulary. Its original meaning is an objective existence reflected in people's consciousness, the result of thinking activities or the formed viewpoint and concept system.
First, explain "thought".
First ask you a question: what kind of person do you want to be?
Maybe you will answer: I want to be a good person, honor my parents, respect my elders and care for my relatives and friends... You see, this is the idea. This is your idea of life, or your principle of life.
Being a man has the principle of being a man, and programming also has the principle of programming. These programming principles are programming ideas.
The so-called programming thought refers to the way of thinking of using computers to solve people's practical problems.
It's like learning a course. First of all, we should be familiar with the basic concepts of the course, and then learn the conclusions drawn from the definition. After learning a book, the most important thing for us is the construction of knowledge system, which is closely related to programming ideas.
When we do something, this method is reasonable:
1. First divide a problem into small modules, just like the relationship from book to chapter;
2. Divide a small module into smaller parts, just like the relationship from chapter to section;
3. Finally divide them into inseparable parts, just like the relationship from section to definition and concept;
4. This is just like realizing the function of a program. First consider the general direction, and then realize it step by step, so as to avoid repetition and leakage.
1.2 process oriented programming
Process oriented programming (POP) is a process centered programming idea. These are programming with the goal of what is happening, different from object-oriented who is affected. The obvious difference from object-oriented is encapsulation, inheritance and class.
Features: modularity and flow.
Advantages: the performance is higher than that of object-oriented, because class calls need to be instantiated, which costs a lot and consumes resources. Single chip microcomputer, embedded development and Linux/ Unix generally adopt process oriented development, and performance is the most important factor.
Disadvantages: no object-oriented, easy to maintain, easy to reuse and easy to expand.
Process oriented: write code from top to bottom according to business logic. Process oriented programming is most easily accepted by beginners. It often uses a long piece of code to realize the specified functions. The idea of the development process is to organize the data and functions together according to the logical order of execution, and consider the data and functions separately.
1.3 object oriented programming
Object Oriented Programming (OOP) is a method to analyze, design and implement software by establishing a model based on the concept of object (entity) according to the systematic thinking mode of people's understanding of the objective world. Through the object-oriented concept, the computer software system can correspond with the system in the real world one by one.
Characteristics: Abstract encapsulation inheritance polymorphism.
Advantages: easy to maintain, reuse and expand. Due to the characteristics of object-oriented encapsulation, inheritance and polymorphism, a low coupling system can be designed to make the system more flexible and easier to maintain.
Disadvantages: lower performance than process oriented.
1.4 difference between process oriented and object-oriented
Both of them are a kind of thought, and object-oriented is relative to process oriented.
Process oriented is to analyze the steps needed to solve the problem, and then use functions to realize these steps step by step. When using, you can call them one by one; Process oriented, emphasizing the functional behavior, taking the function as the minimum unit, consider how to do it.
Object oriented is to decompose the problem into various objects. The purpose of establishing objects is not to complete a step, but to describe the behavior of something in the whole problem-solving step; Object oriented, encapsulating functions into objects, emphasizing the objects with functions, taking class / object as the minimum unit, and considering who will do it.
Process oriented program features: emphasis on implementation functions, algorithms and all details
Characteristics of object-oriented program: emphasize the object with function
Object oriented emphasizes the use of human thinking methods and principles in daily thinking logic, such as abstraction, classification, inheritance, aggregation, polymorphism and so on.
Case description:
People put elephants in the refrigerator: Process oriented: Function 1: open the refrigerator() {The man stood in front of the refrigerator and opened the refrigerator. When the refrigerator was opened to a 30 degree angle, the light of the refrigerator turned on....} Function 2: store elephant() {The elephant takes his left leg first, then his right leg, and considers whether the refrigerator can hold it...} Function 3: turn off the refrigerator() {People stand in front of the refrigerator and close the refrigerator. When the refrigerator is closed to a 30 degree angle, the light of the refrigerator goes out....} object-oriented: people{ open(Refrigerator) { Refrigerator.open(); } Store(elephant) { elephant.get into(Refrigerator); } close(Refrigerator) { Refrigerator.close(); } } Refrigerator{ open() {} close() {} } elephant{ get into(Refrigerator) {} } Process oriented--->Object oriented is actually a transition from executor to commander. The two complement each other, not opposite. To solve complex problems, the object-oriented method is convenient for us to grasp the complex relationship between things from the macro level, and it is convenient for us to analyze the whole system. From the specific to the micro operation, we still use the process-oriented method to deal with it. How to understand and solve complex problems and make object-oriented more efficient? For example, there is a company that has just started; Total 4-5 Employees, the company's business is relatively small, things happen, we do it together; This will be more efficient, which is the process oriented approach; However, if the company becomes larger and larger, with 400 or 500 employees, it will obviously be very chaotic if it is realized in the above way; Then it is necessary to divide the marketing department, procurement department, production department and customer service department, and divide the responsibilities of each department(This is equivalent to the design of classes),When something happens, go to the person in the corresponding department according to the business(This is equivalent to finding objects based on classes)OK; Others say, Process oriented: Chronology (explain who did what according to the year and time) Object oriented: Ji chuanti (explain what a person did at different times)
1.5 ideas and steps of object-oriented analysis
Programmers have transformed from process oriented executors to object-oriented commanders.
Ideas and steps of analyzing problems with object-oriented analysis method:
According to the needs of the problem, select the 'real-world entity' targeted by the problem.
Looking for the attributes and functions related to solving problems from entities, these attributes and functions form the "class in the conceptual world".
Abstract entities are described in computer language to "form the definition of classes in the computer world". That is, with the help of a program language, the class is constructed into a data structure that can be recognized and processed by the computer.
Instantiate a class as an object in the computer world. Object is the ultimate tool to solve problems in the computer world.
2, Java basic elements: classes and objects
What is the world made of?
The world is composed of conceptual world and material world. The conceptual world includes the sum of all life's cognition of the objective world and the things that exist to record cognition; The material world, that is, objective existence, refers to the world that does not depend on human consciousness and can be reflected by human consciousness. It includes nature and human society in a narrow sense.
Java is a mapping of the real world. In the Java world, everything is an "object".
2.1 overview of object-oriented idea
Class and object are the core concepts of object-oriented.
Class is the description of a class of things, which is an abstract and conceptual definition.
An object is each individual of such things that actually exist, so it is also called an instance.
It can be understood as: class = vehicle design drawing; Object = real car;
The focus of object-oriented programming is the design of classes.
Class design is actually the design of class members.
2.1.1 extract "class" from object
Extract the common characteristics of the properties and methods of the following objects:
Classification is a very natural process for people to understand the world. They will classify unconsciously in their daily life.
Classes in the real world: humans, cats, cars......
Objects in the real world: Zhang San, a white cat, a Mercedes Benz...
Class: an abstract concept that extracts the same features from a series of objects. Object is the concretization of class, that is, the individual of this kind of things.
So class is an abstract definition of things in the real world. This abstract definition can basically describe something clearly In order to describe things clearly, we must know what characteristics (data, saved with variables) and what behaviors (described with methods) things have. When the characteristics and behaviors of something are described clearly, we think we have a general grasp of the thing
1. You can simplify complex things
2. Leave professional things to professional people
3. In modern society, cooperation is emphasized, and object-oriented reflects this idea ("new interpretation of barrel theory, emphasizing long board effect")
4. Computer is the simulation of the real world. Only by adopting the idea of object-oriented can we better simulate, serve and transform the world.
2.1.2 object is the concretization of class
An object is a real entity of a class, also known as an instance, so an object is also known as an instance. An instance is an object and an object is an instance
For example, "student" can be a class, because it describes the group of students, and the specific "Xiaoming in grade 3" is an object, and the same "Xiaohua in grade 4" is also a student object
Comparison chart:
2.1.3 first object or first class
In object-oriented thinking, whether there is an object or a class first, at first glance, is a kind of problem with whether there is an egg or a chicken first.
In real life, there are objects first, which are abstracted from objects into classes. In programming, it is the opposite, which is instantiated from abstract classes into objects.
2.1.4 understand "everything is an object"
1. In the category of Java language, we all encapsulate functions and structures into classes, and call specific function structures through class instantiation
> scanner, string, etc
> File: File
> network resources: URL
2. When it comes to the interaction between the Java language and the front-end Html and back-end databases, the front and back-end structures are embodied as classes and objects at the Java level.
2.1.5 category and object summary
In the Java world, a class refers to a data type.
In Java, class is the carrier of code, and all code should be written in class.
In Java, classes include: JDK built-in, third-party developed, self-developed classes...
In the Java world, an object refers to an individual (instance) of a type running in memory (heap).
A group of things with the same characteristics is usually a class, which is an abstract definition existing in the human brain.
Class is a model and does not have any function in itself. For example, a cake mold can make a cake, but it can't be eaten.
Object is the concretization of class, that is, the individual of this kind of things.
Classes describe things (objects). Once they are clearly described, they can represent a class of things. However, classes are just concepts. If you want to use entities, you must have objects. However, in terms of time order, there are classes before objects, because classes are like a template, and objects are like products made from this template, as described in the previous figure, Automobile design drawing is a template. Once you have this template, you can use the design drawing to manufacture automobiles without limitation
2.2 Java classes and class members
Organisms in the real world, ranging from whales to ants, are made up of the most basic 'cells'. Similarly, the Java code world is composed of many 'classes' with different functions.
class is used to describe things in Java. Things have static characteristics such as size, color, quality, height, fat and thin, and these characteristics can be described by data types. Variables are the ones that save data in the program. Things also have behaviors, such as eating, running, jumping, sleeping, etc., and the description of these behaviors is a little more complex than variables. Methods are used to describe the behavior of things.
Common class members are:
Attributes: static characteristics of objects
Attribute - various characteristics of the object;
Each attribute of each object has a specific value. For example, Zhang Hao and Li Ming have different ages and names;
Member variables in the corresponding class;
Methods: dynamic features of objects
Method - the operation performed by the object, for example: Cashier Li Ming's method: card swiping, order printing, cashier;
Member methods in corresponding classes;
Field = attribute = member variable = instance variable, Method = function = (member) Method = instance Method;
Create class object = instantiation of class = instantiation of class;
2.3 syntax format of Java classes
All Java programs are organized by class
Keyword class defines class type data
All classes are reference data types.
To define a class
1. Definition class
2. Write class attributes (member variables)
3. Write class methods (member methods)
Define the syntax of the class:
Modifier class name{
/ / define the attribute part
Type of attribute 1;
Type of attribute 2;
...
Type of attribute n;
/ / define method
Method 1;
Method 2;
...
Method m;
}
Description:
Modifier public, the class can be accessed arbitrarily
Class simulates real-world concepts into computer programs
Example code:
public class Person { String name; // The variable name declared in the class is an attribute, also known as a member variable, and the descriptor has a name int age; // The variable age declared in the class is the attribute, also known as the member variable, which describes the age of the person public void play() { // Declare the method play(), also known as the member method, which means that people can play System.out.println("Play behavior"); } }
2.4 membership of Java classes
2.4.1 easy version
public class Person { // Property or member variable or instance variable String name; int age; boolean isMarried; // Function or member method or instance method public void walk() { System.out.println("The act of walking..."); } public String disPlay() { return "The name is:" + name + ",Age is:" + age + ",Married or not:" + isMarried; } }
2.4.2 full version
public class Person { // Property or member variable or instance variable String name; int age; boolean isMarried; // Constructor or constructor public Person() { } public Person(String name, int age, boolean isMarried) { this.name = name; this.age = age; this.isMarried = isMarried; } // Function or member method or instance method public void walk() { System.out.println("The act of walking..."); } public String disPlay() { return "The name is:" + name + ",Age is:" + age + ",Married or not:" + isMarried; } // Construct code block { name = "Zhang San"; age = 18; isMarried = true; } // Inner class class Pet { String name; int age; float weight; } }
2.5 creating Java custom classes
Steps:
1. Define class (consider modifier and class name)
2. Write the attributes of the class (consider modifier, attribute type, attribute name and initialization value)
3. Write methods of classes (consider modifiers, return value types, method names, formal parameters, etc.)
Exercise:
Define Person, Animal, ClassRoom, Zoo and other classes and experience them.
2.6 implementation of object-oriented idea
1. Create a class and design the members of the class
2. Create an object of class
3. Call the structure of an object through object. Property or object. Method
//1. Create a class and design the members of the class class Person { //attribute String name; int age = 1; boolean isMale; //method public void eat() { System.out.println("People can eat"); } public void sleep() { System.out.println("People can sleep"); } public void talk(String language) { System.out.println("People can talk,Used are:" + language); } } //Test class public class PersonTest { public static void main(String[] args) { //2. Create the object of Person class Person p1 = new Person(); //Scanner scanner = new Scanner(System.in); // 3. Call properties and methods // Structure of calling object: attribute and method // Calling property: "object. Property" p1.name = "Tom"; p1.isMale = true; System.out.println(p1.name); // Calling method: "object. Method" p1.eat(); p1.sleep(); p1.talk("Chinese"); } }
3, Creation and use of Java objects
After the class definition is completed, it cannot be used directly. If you want to use, you must rely on the object. Since the class belongs to the reference data type, the object generation format (two formats) is as follows:
Format 1: declare and instantiate objects
Class name object name = new class name ();
Format 2: declare the object first, and then instantiate the object:
Class name object name;
Object name = new class name ();
The biggest difference between reference data type and basic data type is that reference data type requires memory allocation and use. Therefore, the main function of the keyword new is to allocate memory space, that is, as long as the reference data type is used, the keyword new should be used to allocate memory space.
After an instantiated object is generated, you can operate the class as follows:
Object Attribute: indicates the attribute in the calling class;
Object Method (): refers to the method in the calling class.
3.1 using object operation classes
3.1.1 create object syntax i
public class TestDemo { public static void main(String args[]) { // create a class object Person per = new Person(); //Operation properties per.name = "Zhang San"; per.age = 30; //Call the get() method in the class per.get(); } } class Person { String name; int age; public void get() { System.out.println("full name:" + name + ",Age:" + age); } }
Operation results:
Name: Zhang San, age: 30
3.1.2 create object syntax II
The above completes the operation relationship between a class and an object. Let's change another operation to observe:
public class TestDemo { public static void main(String args[]) { // Declaration object Person per = null; // Instantiate object per = new Person(); // Operation attribute content per.name = "Zhang San"; per.age = 30; per.get();//Call the get() method in the class } } class Person { String name; int age; public void get() { System.out.println("full name:" + name + ",Age:" + age); } }
Operation results:
Name: Zhang San, age: 30
So, here's the question. What's the difference between the above two different instantiation methods?
3.1.3 Java object memory parsing
We analyze it from the perspective of memory. Firstly, two concepts of memory space are given:
(1) heap memory: store the objects and arrays created by new and the instance variables (attribute contents) of the objects. Heap memory needs to allocate space with the new keyword.
(2) stack memory: it stores basic types of variable data, local variables and object references, but the object itself is not stored in the stack.
Understanding of null:
First, null is not a valid object instance, so no memory is allocated for it. It is just a value indicating that the object reference does not currently reference the object.
From JVM specification:
The Java Virtual Machine specification does not mandate a concrete value encoding null. (the Java virtual machine specification does not authorize a specific value encoding null.)
In any case, as long as you see the keyword new, it means that you want to allocate a new heap memory space. Once the heap memory space is allocated, there will be attributes defined in the class, and the attribute content is the default value of its corresponding data type.
Therefore, the above two object instantiation methods are represented as follows:
The difference between the two methods lies in ① and ②. The first method of declaration and instantiation is actually ① and ② combined together, while the second method of declaration and instantiation is to take ① and ② step by step.
In addition, if an object without instantiation is used, what is the result?
public class TestDemo { public static void main(String args[]) { // Declaration object Person per = null; // per = new Person() ;// Instantiate object //Operation properties and methods per.name = "Zhang San"; per.age = 30; per.get(); } } class Person { String name; int age; public void get() { System.out.println("full name:" + name + ",Age:" + age); } }
Operation results:
Exception in thread "main" java.lang.NullPointerException
at com.wz.demo01.TestDemo.main(TestDemo.java:15)
At this time, the program only declares the Person object, but does not instantiate the Person object (only stack memory, no corresponding heap memory space). The program will not have any errors during compilation, but the above error message appears during execution. This error message indicates "null pointerexception", which can occur as long as it is a reference data type.
3.1.4 object reference transfer analysis
If you create multiple objects of a class, each object has an independent set of class properties. (non static), which means that if we modify attribute a of one object, the value of attribute a of another object will not be affected.
The essence of reference passing: the same heap memory space can be pointed by multiple stack memories at the same time. Different stacks can modify the contents of the same heap memory.
The following explains the code through several programs and the memory allocation diagram of the program.
public class TestDemo { public static void main(String args[]) { Person per1 = new Person(); // Declare and instantiate objects per1.name = "Zhang San"; per1.age = 20; // Instead of creating a new object, let per2 point to the address of per1 Person per2 = per1; // Reference passing per2.name = "Li Si"; per1.tell(); } } class Person { String name; int age; public void tell() { System.out.println("full name:" + name + ",Age:" + age); } }
The corresponding memory allocation diagram is as follows:
Let's look at another one:
public class TestDemo { public static void main(String args[]) { Person per1 = new Person(); // Declare and instantiate objects Person per2 = new Person(); per1.name = "Zhang San"; per1.age = 20; per2.name = "Li Si"; per2.age = 30; per2 = per1;// Reference passing per2.name = "Wang Wu"; per1.tell(); } } class Person { String name; int age; public void tell() { System.out.println("full name:" + name + ",Age:" + age); } }
Garbage: refers to a heap memory space that is not pointed to by any object during program development. This space becomes garbage. All garbage will wait for GC (garbage collector) to recycle and release space irregularly.
3.1.5 deep parsing of Java object memory
Object generation
// Class is defined as follows class Person { int age; void shout() { System.out.println("oh, my god !I am "+age); } }
Person p1 = new Person(); Memory status after execution.
Use of objects
class PersonTest { public static void main(String[] args) { Person p1 = new Person(); Person p2 = new Person(); p1.age = -30; p1.shout(); p2.shout(); } } //The memory layout of the program is shown below
Object lifecycle
JVM memory region model
Method area: Also called"Permanent generation "," non heap ", which is used for storage'Class information, constants and static variables loaded by the virtual machine',Is the memory area shared by each thread. The default minimum value is 16 MB,The maximum value is 64 MB,Can pass-XX:PermSize and -XX:MaxPermSize Parameter limits the size of the method area. Runtime constant pool: it is part of the method area, Class In addition to the class version, field, method, interface and other description information, there is also a constant pool, which is used to store various symbol references generated by the compiler. This part will be put into the runtime constant pool in the method area after the class is loaded. VM Stack : The description is java Memory model of method execution: when each method is executed, a "stack frame" will be created to store the local variable table(Include parameters),Operation stack, method exit and other information. The process from the call of each method to the completion of execution corresponds to the process of a stack frame from entering the stack to leaving the stack in the virtual machine stack. The declaration cycle is the same as the thread and is thread private. The local variable table stores various basic data types known to the compiler(boolean,byte,char,short,int,float,long, double),object reference(Reference pointer, not the object itself),Where 64 bit length long and double Type of data will occupy the space of 2 local variables, and other data types only occupy 1. The memory space required by the local variable table is allocated during compilation. When entering a method, how many local variables this method needs to allocate in the stack frame is completely determined. During operation, the stack frame will not change the size and space of the local variable table. Native Method Stack : It is basically similar to the virtual machine stack, except that the virtual machine stack is executed by the virtual machine java Method service, while the local method stack is Native Method services. heap: Also called java Heap GC Heap is java The largest memory area in the memory managed by the virtual machine, which is also shared by various threads JVM Created at startup. This memory area stores object instances and arrays(All new Object of). Its size passes-Xms(minimum value)and-Xmx(Maximum)Parameter setting,-Xms by JVM The minimum memory requested at startup is 1% of the physical memory of the operating system by default/64 But less than 1 G,-Xmx by JVM The maximum memory that can be applied for. The default is 1 of the physical memory/4 But less than 1 G,By default, when the free heap memory is less than 40%When, JVM Will increase Heap reach-Xmx The specified size can be-XX:MinHeapFreeRation=To specify the comparison column; When the free heap memory is greater than 70%When, JVM Will decrease heap Size to-Xms The specified size can be XX:MaxHeapFreeRation=To specify this ratio column, for the running system, in order to avoid frequent adjustment at run time Heap Size, usually-Xms And-Xmx Set the value of to the same. Since the collectors now adopt the generational collection algorithm, the heap is divided into the new generation and the old generation. The new generation mainly stores newly created objects and objects that have not yet entered the old age. The old generation storage has gone through many new generations GC(Minor GC)Still alive. New generation: the objects newly created by the program are allocated memory from the new generation, which is composed of Eden Space And two pieces of the same size Survivor Space(Usually also known as S0 and S1 or From and To)Composition, available through-Xmn Parameter to specify the size of the Cenozoic, or through-XX:SurvivorRation To adjust Eden Space and Survivor Space The size of the. Old age: used to store the Cenozoic after many times GC Surviving objects, such as cache objects, and newly created objects may also directly enter the elderly generation. There are two main situations:①.Large objects can be set by starting parameters-XX:PretenureSizeThreshold=1024(The unit is byte, and the default is 0)To represent how old they are, they are not distributed in the new generation, but directly in the old generation.②.Large array objects, no reference to external objects in the tangent array. The memory size of the older generation is-Xmx Corresponding value minus-Xmn Corresponding value. Program counter: Its function is the line number indicator of the bytecode executed by the current thread. In the virtual machine model, the bytecode interpreter works by changing the value of this counter to select the next bytecode instruction to be executed. The basic functions such as branch, loop, exception handling and thread recovery need to be completed by the counter. JVM Detailed explanation of memory area( Eden Space,Survivor Space,Old Gen,Code Cache and Perm Gen): https://blog.csdn.net/shiyong1949/article/details/52585256 Cenozoic era GC,Old age GC: https://www.cnblogs.com/luao/p/10644124.html
3.2 class access mechanism
Access mechanism in a class: Methods in a class can directly access member variables in a class. (exception: static method accesses non static, and compilation fails.)
Access mechanism in different classes: first create the object to access the class, and then use the object to access the members defined in the class.
3.3 anonymous objects in classes
An object without a name is called an anonymous object;
According to the previous memory relationship, the name of the object is in the stack memory, and the specific contents of the object are saved in the heap memory. In this way, if there is no stack memory pointing to the heap memory space, it is an anonymous object.
Usage:
If you only need to make one method call to an object, you can use anonymous objects.
We often pass anonymous objects as arguments to a method call.
public class AnonymityTest { public static void main(String[] args) { // Named object: refers to the address of an object in heap memory through a variable // We call the method by pointing to the new object through the variable name Animal animal1 = new Animal(); // Multiple use animal1.name = "Cerebellar axe"; animal1.age = 6; animal1.show(); // Anonymous object: an object in object memory has no variables pointing to it // Two anonymous objects call show() once respectively; // new Animal().show(); // new Animal().show(); // Scenario 1: if you only need to make one method call to an object, you can use anonymous objects. new Animal().name = "Big flower cat"; new Animal().show(); //null 0 // Scenario 2: we often pass anonymous objects as arguments to a method call. /*Phone phone = new Phone(); phone.name = "Apple "; phone.price = 8888.88;*/ People people = new People(); people.talk(new Phone()); } } class Animal { String name; int age; void show() { System.out.println("Name is:" + name + "\t" + age); } } /* * human beings * */ class People { String name; int age; /* * Methods of human communication * */ void talk(Phone phone) { phone.call(); phone.email(); phone.social(); } } /* * Mobile phone class * */ class Phone { String name; double price; // phone void call() { System.out.println("Make a phone call with your mobile phone"); } // send emails void email() { System.out.println("Send e-mail on your mobile phone"); } // Social software void social() { System.out.println("Use the social software in your phone"); } }
Operation results:
Construction method with two parameters
Book Name: Java development book price: 89.9
Since the anonymous object has no corresponding stack memory point, it can only be used once. After that, it will become garbage and wait to be recycled and released by GC.