Object oriented 1
1.1 object oriented overview
1.1.1 function encapsulation
The function / method encapsulates the code that specifically implements a certain function, and by writing a class with multiple specific functions, it stores one method after another.
Methods are stored in classes. When you need to use them, you don't need to find specific methods, but find this class first, so you can naturally find the encapsulated methods.
Encapsulate some methods of array operation into ArrayTools. Feel the benefits of encapsulation through the following code.
// Custom int type array public class ArrayTools { // Set attribute external property description private int[] arr;// Meta array private int arrLength;// Length of valid data // Describe the behavior // Create an array of default size public ArrayTools() { arr = new int[50]; } // Creates the specified array public ArrayTools(int maxsize) { arr = new int[maxsize]; } // Add new element public void insert(int target) { arr[arrLength] = target; arrLength++; } // Display array public void display() { System.out.print("[ "); for (int i = 0; i < arrLength; i++) { System.out.print(arr[i] + " "); } System.out.print("]"); } // Find target element location public int search(int target) { int i; for (i = 0; i < arrLength; i++) { if (target == arr[i]) { break; } } if (i == arrLength) { return -1; } return i; } // Gets the element at the specified location public int get(int index) { if (index >= arrLength || index < 0) { throw new ArrayIndexOutOfBoundsException(); } else { return arr[index]; } } // Delete the specified element public void delete(int index) { if (index >= arrLength || index < 0) { throw new ArrayIndexOutOfBoundsException(); } else { for (int i = index; i < arrLength; i++) { arr[i] = arr[i + 1]; display(); } arrLength--; } } }
Method: it is used to encapsulate function code, and class is used to encapsulate functions with a certain class of similar characteristics.
Facing requirements: first find out whether Java provides corresponding classes to meet such requirements. If not, write a class to encapsulate the function.
1.1.2 understanding what is process oriented
Process oriented is also an idea of solving problems. When we solve problems, we will implement them step by step according to the preset ideas and steps, and each specific step needs us to implement and operate. These steps call and cooperate with each other to complete our requirements.
Through the above simple description, it is found that process oriented is actually oriented to each specific step and process, that is, to each specific function. These functions call each other to complete the requirements.
Process oriented representative language: C language.
When the demand is single or simple, we can operate step by step, and find that the efficiency is also very high. However, with the change of requirements and the increase of functions, it is found that each step that needs to be faced has been too busy. At this time, I began to think about whether these steps and functions can be encapsulated according to different functions, with similar functions encapsulated together. When using, just find the entity that encapsulates the function. At this time, we find that we face a specific method over an individual * * that encapsulates a certain type of function.
1.1.3 understanding what object-oriented is
When no longer facing each specific method, the operation becomes much simpler. The class that encapsulates specific functions is what we need to face. Based on this class that encapsulates specific functions, generally, it needs to be used by creating the entity of this class in Java.
This entity is called an object. In development, we are constantly looking for classes that encapsulate different functions. Create its objects based on these classes and use these objects to complete the corresponding operations.
Through the above explanation and analysis, it is concluded that object-oriented is based on process-oriented, and object encapsulates functions. The specific function can be found as long as the specific class is created. Object oriented is also a thinking mode used to solve problems.
In later development, first find the object and call the specific functions in the object. If there is really no object that can complete the requirements, create the object by yourself and define the required functions into the object for later use.
face object (Object Oriented) yes Software development method , a programming paradigm. face object The concept and application of has gone beyond Programming And software development, such as database system , interactive interface, application structure, application platform distributed system ,Network management Structure, CAD technology artificial intelligence And other fields. Object oriented is a method of understanding and abstracting the real world. It is the product of the development of computer programming technology to a certain stage.
OOP(Object Oriented Design): object oriented programming design.
1.2 object oriented example
1.2.1. Buy a computer (assembly machine)
1.2.2 difference between object-oriented and process oriented (benefits of object-oriented)
Summarize process oriented and object-oriented:
- Object oriented is an idea that is more in line with people's thinking habits.
- The executor is more embodied in the process oriented, and the commander is more embodied in the object-oriented. Command the object to do things.
- Object oriented simplifies complex problems.
Summary:
- First refine the objects in the problem field according to the nouns.
- To describe an object is actually to clarify the attributes and functions that should be possessed by the object.
- Through the new keyword, you can create the specific object of the thing.
- Call its subsequent functions through this object. use. Access properties and call methods (e.g. elephant) nose
2. Classes and objects
2.1 class and object
Object oriented programming (OOP) object-oriented programming. An object represents an entity that can be clearly identified in the real world. For example, a student, a desk, a circle, a button or even a loan can be regarded as an object. Each object has its own unique identity, state and behavior.
- The state of an object (also known as a property) is represented by the property (data field) with the current value. For example, a circle has the attribute of radius, and a rectangle has the attributes of width and height.
- The behavior of an object (also known as action) is defined by methods. One method of calling an object is to complete an action as required. For example, you can define a method = = getArea() and getPerimeter() for a circle object. Obtain the area and perimeter of the circle respectively. You can even call setradius(radius) = = to modify the radius of the circle.
Use a common class to define objects of the same type. A class is a template. It is used to define what the properties of the object are and what the methods do. An object is an instance of a class. You can create multiple instances from a class. The process of creating an instance is called instantiation. Objects and instances are often interchangeable. Like apple pie recipe and apple pie. Look at the following class Circle.
public class Circle { public final double PI = Math.PI; // Radius, the default value is 1. double radius = 1; // Construction method 1 public Circle(double radius) { this.radius = radius; } // Construction method 2 public Circle() { } this.radius = radius; } public double getArea(){ return PI*radius*radius; } // Circumference of a circle public double getPerimeter(){ return 2*PI*radius; } } ······································································· // Create three circles Circle circle1 = new Circle(); Circle circle2 = new Circle(); Circle circle3 = new Circle();
Write a class Circle and create instantiated objects of three circles. Create by new keyword + construction method (). Then you can use the created object to complete the access and modification of attributes and the operation of calling methods.
2.2 embodiment of object in code
When analyzing things in real life, we find that these things have their specific characteristics and functions, which constitute this special thing.
Describe the car and analyze its attributes and behavior.
- Characteristics of things (attributes): color, number of tires.
- Behavior (method) of things: operation.
It can be simply understood that an attribute is a value, which is actually a variable; a behavior is a function, which is actually a function.
//Text emulation: //a car { Color; Number of tires; function(){} } // class Car { String color;// colour int number;// quantity void run()// Operation method!!! { System.out.println(color+"::"+number); } }
Through the description of code, we know that the real meaning of class is to describe things. Attributes and behaviors are collectively referred to as members of things.
There are two kinds of members of things: member attributes and member behavior.
Member attribute: the embodiment in the code is the member variable.
Member behavior: the embodiment in the code is the member function (method).
Run the Car class written by the test.
class CarDemo { public static void main(String[] args) { //Test: run method in Car class. //1. Create the object of Car. Give the object a name. Car c = new Car();//c is a variable of class type. c points to a specific Car type object. //2. Call the function of the object through the existing object. Formats: objects Object members; //3. You can assign values to the attributes of the object. c.color = "red"; c.number = 4; c.run(); } }
2.3 memory diagram of object
Analyze the allocation of objects in memory, and explain the creation process of memory objects in strict accordance with the drawing process.
[the transfer of external chain pictures fails, and the source station may have anti-theft chain mechanism. It is recommended to save the pictures and upload them directly (img-iqtold9-160999059557) (D: \ Java class materials \ November 20, 2020 - java3 class \ materials \ 5. Java - object-oriented \ img\image-20200627093219151.png)]
Analyze the memory diagram of the following objects
Analyze the allocation of objects in memory, and explain the creation process of memory objects in strict accordance with the drawing process.
[the transfer of external chain pictures fails, and the source station may have anti-theft chain mechanism. It is recommended to save the pictures and upload them directly (IMG njaldrv8-1609990599563) (D: \ Java class materials \ November 20, 2020 - java3 class \ materials \ 5. Java - object-oriented \ img\image-20200627093340468.png)]
2.4 difference between class and object
Class is used to describe real things. It abstracts and templates real things. Encapsulate the characteristics (attributes) and behavior of things. For example, the drawing of a car is the template of a car. Various features and functional requirements of the car are drawn on the drawing.
Objects are concrete examples and individuals existing in real life. That is, every thing we see in life and the abstract concept of things we imagine are examples and individuals of a certain kind of things. These individuals belong to a certain kind of things, that is, these individuals are specific examples of a certain kind of things. For example, a car is a kind of thing, and a car is a real individual made based on car drawings. Therefore, every object in our life can be understood as an individual of a certain kind of things. Create an object through which you can call specific properties and behaviors.
2.5 differences between local variables and member variables
Through the definition and location of variables in the previous study, as well as the characteristics of attributes in the current definition class. Summarize the following similarities and differences:
-
The defined locations are different.
Member variables are defined in the class.
Local variables are defined in methods or statements.
-
Different locations in memory
Member variables are stored in objects in heap memory.
Local variables are stored in methods in stack memory.
-
Different life cycles
Member variables appear in heap memory with the appearance of objects and disappear in heap memory with the disappearance of objects.
Local variables appear in the stack memory as the method runs, and disappear as the method bounces the stack.
-
Different initialization
Member variables have default initialization values because they are in heap memory.
Local variables have no default initialization value, and they can only be used after being assigned manually.
2.6. Anonymous objects (anonymous objects are passed as parameters)
When using an object, a reference will be created to the object, and the created object will be used through this reference. See the following code:
class Car { //Describe the properties. Color, number of tires. String color; int number; //Describe the behavior. void run() { System.out.println(color+":"+number); } } class CarDemo { public static void main(String[] args) { //Create car Class object. Car c = new Car(); //Call the run method c.run(); //Create car Class object. Car c2 = new Car(); //Call the run method c2.run(); } }
In the main() method, every time an object is created, it is only to call its run () method, and the c reference variable defined at this time has little effect. And c is equivalent to new Car(); In this case, you can use simplified writing to write new car () run();
new Car(); This line of code does not create a reference to the car object, that is, it does not name the object. Such code is called an anonymous object. Anonymous objects can simplify the above code.
class CarDemo { public static void main(String[] args) { //Simplified form of the above code new Car().run(); new Car().run(); } }
To simplify writing, anonymous objects are used. Usage scenario of anonymous object: when an object calls a method only once, it can be simplified into anonymous object to write. For example: Car C = new car (); c.run(); = = = > new Car(). run();
Anonymous objects can also be passed as parameters: draw a picture to illustrate the details of anonymous object passing.
class CarDemo { public static void main(String[] args) { Car c = new Car(); show(c); //Simplified to show(new Car())// Pass anonymous objects as actual parameters. } public static void show(Car cc) // Car cc = c; Car cc = new Car(); { cc.color = "red"; cc.number = 4; cc.run(); } }
2.7. Basic type and reference type are passed as parameters
[the transfer of external chain pictures fails, and the source station may have anti-theft chain mechanism. It is recommended to save the pictures and upload them directly (img-e1d0jh3b-160999059570) (D: \ Java class materials \ November 20, 2020 - java3 class \ materials \ 5. Java - object-oriented \ img \ image-2020062712437446. PNG)]
When a basic type is passed as a parameter, it actually copies the value in the basic type variable x space and passes it to the calling method show(). First, accept the value copied by X in the show() method, and then operate on the X variable in the show() method. At this time, it will only affect the X in show(). When the = = show() method is executed, the program returns to the main() = = method, and the x value in the main() method is still the original value.
[the external chain picture transfer fails, and the source station may have anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-wphQwFYI-1609990599577)(D:\java class materials \ November 20, 2020 - java3 class \ materials \ 5. Java - object-oriented \ img \ image-202006271724559. PNG)]
When a reference variable is passed as a parameter, the memory address (Reference) in the reference variable space is copied to the d reference variable passed to the show () method. At this time, two references point to the same object in the heap at the same time. When d.x=6 in the show() method is executed, the object in the heap will be found according to the reference held by d, and the value of its x attribute will be changed to 6, and then = = show() = = method will pop up the stack.
Since two references point to the same object, no matter which reference changes the value in the object pointed to by the reference, other references use the changed value again.
class Demo { int x ; public static void main(String[] args) { Demo d = new Demo(); d.x = 5; show(new Demo()); System.out.println("x="+d.x); } public static void show(Demo d) { d.x = 6; } }
3. Encapsulation
3.1 packaging concept
In the previous code, * * specific functions were encapsulated in methods, and methods were encapsulated in classes * * in objects. In fact, these are encapsulation.
Packaging performance:
- Function is a basic encapsulation.
- Class is also a wrapper.
From the above two points, it can be concluded that the benefits of packaging are:
- It improves the reusability of the code.
- It hides the implementation details and provides external access. It is convenient for callers to use, which is also one of the core. It can also be understood as the concept of encapsulation.
- Improved security.
It is also one of the characteristics of object-oriented thought. Object oriented has three characteristics: encapsulation, inheritance and polymorphism.
3.2. Packaging examples
Computer host chassis components:
A computer is composed of CPU, motherboard, graphics card, memory, hard disk, power supply and other components. In fact, we can use the computer by assembling these components together, but we find that these components are scattered outside, which is likely to cause unsafe factors. Therefore, the chassis shell is used to install these components inside, and some sockets are left on the chassis shell to facilitate external use and expansion.
Conclusion: the chassis actually hides the details of card handling equipment and provides external access to internal details such as sockets and switches.
3.3. Access modifier: private
Observe the following packaging examples and analyze the problems.
/** * Describe the person. Person * Attribute: age. * Behavior: speak: say your age */ public class Person { int age ;// Age String name;// full name public void show()// Exhibition { System.out.println("age="+age+",name"+name); } } class PersonDemo { public static void main(String[] args) { //Create Person object Person p = new Person(); p.age = -20; // Assign a value to the Person object p.name = "Simon?"; p.show(); //Call the show method of Person } }
Through the above code, it is found that although we use Java code to describe Person clearly, there is a serious problem that the properties and behaviors in Person can be accessed and used arbitrarily, which obviously does not meet the actual needs.
But how can we not allow access? You need to use a keyword in Java, which is also a modifier private (private, permission modifier). As long as the properties and behaviors of Person are private, they cannot be accessed directly.
class Person { private int age ; private String name; public void show() { System.out.println("age="+age+",name"+name); } }
Age has been privatized. The wrong value cannot be assigned, but the correct value cannot be assigned. This is still not possible. What should we do? According to the principle of encapsulation learned before, access mode needs to be provided after hiding. As long as accessible methods are provided externally, let other programs access these methods. At the same time, the data can be verified in the method.
General access actions to member attributes: assignment (set) and value (get). Therefore, the corresponding setXXX () or getXxx() methods can be provided for accessing private variables`` setXxx()/getXxx ` is just the recommended way of writing *, not necessarily *.
class Person { // Private member variable private int age ; private String name; // Provides methods for setting member variables externally public void setAge(int a) { // Since it is to set the value of member variables, data validation can be added here if( a < 0 || a > 130 ) { System.out.println(a+"Data range not in line with age"); return; } age = a; } // Provide external access to member variables public void getAge() { return age; } }
Summary:
All contents in the class that do not need to be provided externally are privatized, including properties and behaviors.
We will describe things later. The properties are privatized, and setXxx and getXxx methods are provided to access them.
Note: private is just the embodiment of encapsulation.
Since the attributes in Person are all private, the outside world cannot directly access the attributes. Corresponding setXxx() and getXxx() methods must be provided. When creating a Person object, its name and age should be specified as soon as the Person object is created. What should I do?
3.4 introduction to constructor
In development, it is often necessary to specify the attribute value of the object while creating the object. For example, when an employee is employed, the company should specify his name, age and other attribute information.
To create an object, you need to specify the attribute value. You can use the constructor.
Constructor: literally, it refers to the function used in the construction and creation, that is, the function to be executed when the object is created. Since it is the function to be executed when the object is created, as long as you know what the constructor is when the new() object is executed, you can assign properties to the object when the function is executed.
Format of constructor: Modifier constructor name(parameter list) { }
Features of constructor:
- Constructor has no return value type. There is no need to write the return value. Because = = it is used to build the object. After the object is created, the execution of the function ends = =.
- Constructor name must be consistent with class name.
- Constructor has no specific return value.
//The code embodiment of constructor: class Person { //Member properties age and name of Person private int age; private String name; //Constructor of Person, with parameter list Person(int a , String nm) { //Accept the value passed in when creating the object and assign the value to the member property age = a; name = nm; } }
3.5. Constructor call and memory diagram
When describing a thing, it also describes the constructor. How does the constructor execute? Constructors are specifically used to create objects, that is, constructors are called on new objects. Now let's see how to call the constructor.
class Person { //Member properties age and name of Person private int age; private String name; //Constructor of Person, with parameter list Person(int a , String nm) { //Accept the value passed in when creating the object and assign the value to the member property age = a; name = nm; } public void speak() { System.out.println("name="+name+",age="+age); } } class PersonDemo { public static void main(String[] args) { //Create Person object //Person p = new Person(); // If other construction methods are defined, there will be no Person() for empty construction //The above code compilation reports an error because there is no constructor such as Person() in the Person class //Create a Person object and specify the age and name of the object Person p2 = new Person(23,"Zhang San"); p2.speak(); } }
When the above constructor is called, the code shown above is created. That is, when creating an object, the constructor corresponding to the parameter list will be called.
Illustration of the above code:
[the external chain picture transfer fails, and the source station may have anti-theft chain mechanism. It is recommended to save the picture and upload it directly (IMG teypsfxa-1609990599581) (D: \ lecturer work \ formal course \ lesson plan - final version \ phase I \ 5. Java - object-oriented \ img\image-20200627132414041.png)]
Illustration:
- First, press the main() function into the stack and execute the new Person(23, "Zhang San") in the main() function;
- Allocate an area in the heap memory to store the created Person object. This memory area will have its own memory address (0x88). Then initialize the member variable by default (name = null, age = 0).
- Execute the code (age = a; name = nm;) in the constructor (some knowledge will be omitted here and explained later), After the execution of this code, the values of the member variables age and name have changed. This step is also called constructor initialization. After execution, the constructor pops up the stack and the Person object is created. Assign the memory address 0x88 of the Person object to p2.
3.6 default constructor and details
When describing things, the specified constructor is not displayed. When compiling java files, the compiler will automatically add the default constructor to the class file. If the constructor is specified when describing things, the compiler will not add the default constructor to the class file when compiling the Java source file.
class Person { //If the specified constructor is not displayed, the compilation will automatically add the default constructor at compile time //Person() {} / / default constructor for null parameter }
When describing things, do you want to write constructors in your classes? When the constructor is created, the value of the object description needs to be defined according to the characteristics of the object. If you don't need specific data when creating an object, you don't need to write a constructor (there is also a default constructor if you don't write).
Constructor details:
- A class can have multiple constructors, which exist in the form of overloading.
- There is also a return statement in the constructor, which is used to end the initialization action.
- Constructor can be modified by private. Function: other programs cannot create objects of this class.
class Person { private int age; private String name; //Private parameterless constructor, that is, the outside world cannot pass new Person(); Statement to create this class object private Person() { } //Multiple constructors exist as overloads Person(int a) { age = a; } Person(String nm , int a) { name = nm; age = a; } }
Understand clearly: the difference between constructor and ordinary function.
3.7 differences between constructors and general functions
The constructor is executed when the object is created, and only once.
A general function is called by an object when it needs to be used after the object is created, and can be called multiple times.
Question: after having a constructor, you can initialize the properties of the object. Do you still need the corresponding set and get methods?
Corresponding setXxx() and getXxx() methods are required, because the object needs to modify and access the corresponding attribute value after creation. At this time, it can only be operated through setXxx() or getXxx() methods.
3.8. this calls the constructor
When learning the call between functions before, you can call through the function name. However, for constructors, you cannot call each other through the constructor name.
Calls between constructors can be done through the this keyword.
class Person { // Member properties of Person private int age; private String name; //Parameterless constructor Person() { } //Constructor initialized for name Person(String nm) { name = nm; } //Constructor initialized for name and age Person(String nm , int a) { //Since there is already a constructor to initialize the name, name = nm; So just call //To call other constructors, you need to call them through the this keyword this(nm); //Initialize age age = a; } }
The mutual calls between constructors can be completed through the this keyword.
Constructor call format:
This (parameter list);
Self invocation of method
this. XXX (parameter list)
3.9 schematic diagram of this
Illustrate this keyword and constructor:
class Person { private int age; private String name; Person() { } Person(String nm) { // this -- points to the current object name = nm; } Person(String nm , int a) { // this -- points to the current object this(nm);// Equivalent to Person(nm) age = a; } } class PersonDemo { public static void main(String[] args) { Person p = new Person("Zhang San",23); } } // When creating an object, you see the new keyword. There are new objects // The constructor is only to further initialize the attribute. The real object to create is new + constructor ()
[the transfer of external chain pictures fails, and the source station may have anti-theft chain mechanism. It is recommended to save the pictures and upload them directly (IMG ezitkqqt-160999059584) (D: \ lecturer work \ formal course \ lesson plan - final version \ phase I \ 5. Java - object-oriented \ img \ image-202006271347273. Png)]
Illustration:
- First execute the main() method, press the stack with the main() method, and execute the new Person("Zhang San", 23);
- Open up space in heap memory and allocate memory address 0x33 for it, followed by default initialization of member variables (name = null, age = 0);
- The constructor (Person (string nm, int a)) with two parameters is stacked. There is an implicit this in this constructor, because the constructor initializes the object. Which object calls this constructor, this points to the object created by the constructor in the heap.
- Because this(nm) is used in the Person(String nm, int a) constructor; The constructor Person(String nm) will press the stack and pass "Zhang San" to nm. There is also an implicit this in the Person(String nm) constructor, and the value of this is also 0x33. In this case, name = nm will be executed, that is, assign "Zhang San" to the name of the member. When the assignment is completed = = Person(String nm) = = constructor pop-up stack.
- The program continues to execute age = a in the constructor Person (string nm, int a); At this time, 23 is assigned to the member attribute age. The assignment end constructor Person (string nm, int a) pops up the stack.
- When the constructor Person (string nm, int a) pops the stack, the Person object is created in memory, and 0x33 is assigned to the p reference variable in the main() method.
be careful:
What does this stand for? This represents an object. Which object does it represent? Which object calls the function where this is located, this represents which object.
The first reason to call the constructor is that the first line of the constructor must be initialized.
3.10. Homonymy of member variables and local variables
When the local variable and the member variable have the same name in the function, how to distinguish the local variable and the member variable in the method? You can add this before the member variable name to distinguish member variables from local variables
class Person { private int age; private String name; //Constructor initialized for name and age Person(String name , int age) { //When you need to access a member variable, you only need to add this before the member variable that will do this.name = name; this.age = age; } public void speak() { System.out.println("name="+this.name+",age="+this.age); } } class PersonDemo { public static void main(String[] args) { Person p = new Person("Zhang San",23); p.speak(); } }
3.11 application of this
class Person { private int age; private String name; //Constructor initialized for name and age Person(String name , int age) { //When you need to access a member variable, you only need to add this before the member variable that will do this.name = name; this.age = age; } public void speak() { System.out.println("name="+this.name+",age="+this.age); } //Judge whether they are peers public boolean equalsAge(Person p) { //Compares the age that currently calls the equalsAge method object with the age that is passed in p. //Since it is impossible to determine which object calls the equalsAge method, this can be used instead /* if(this.age == p.age) { return true; } return false; */ return this.age == p.age; } } this.attribute this(parameter list) this.method()
4. static keyword
4.1. static keyword - Overview
When defining a class, there will be corresponding properties and behaviors in the class. The properties and behaviors are called by creating this kind of object. When a behavior of an object is called and the behavior does not access the unique data of the object, it is redundant to call a method to create the object. However, without creating an object, the behavior cannot be called. At this time, we will think, can we call the behavior without creating an object?
class Person { private int age; private String name; Person(int age,String name) { this.age = age; this.name = name; } //The act of speaking, saying your age and name void speak() { System.out.println("name="+this.name+",age="+this.age); } //Sleeping behavior void sleep() { System.out.println("sleep ZZZzzz...."); } } class PersonDemo { public static void main(String[] args) { Person p = new Person(23,"Zhang San"); p.speak(); p.sleep(); } }
It makes no sense to create an object just to call the sleep() method. If the sleep() method needs to be called multiple times, multiple Person objects will be created, which is even more redundant.
4.2. static keyword - modifier function
If you create an object to call a method and find that the method does not use the unique data in the object, then the object is created only to call the method, which appears that the object has been created more than enough. At this time, you can use the static keyword to modify the method.
If a method is modified by static keyword, it belongs to the method of class and can be called directly by class name.
class Person { private int age; private String name; Person(int age ,String name) { this.age = age; this.name = name; } //The act of speaking, saying your age and name void speak() { sleep(); System.out.println("name="+this.name+",age="+this.age); } //Sleep behavior, because the sleep method does not access the unique data of the object, you can use static modification static void sleep() { System.out.println("sleep ZZZzzz...."); } } class PersonDemo { public static void main(String[] args) { //sleep method is a static method and belongs to a class method. You can directly call new Person() using the class name Person.sleep(); } }
When to use static modification methods?
When defining a function, if the function does not need to access the member variables (non static) defined in the class, the function needs static modification.
4.3 precautions for the use of static method
Through the above demonstration, it is found that non static properties and methods cannot be accessed in statically modified methods.
- Static is loaded as the class is loaded. It also disappeared with the disappearance of classes.
- Static takes precedence over objects and is shared by all objects.
- Because statics exist in memory first and cannot access the data in subsequent objects, * * statics cannot access non statics * *. And this cannot be written inside. Because the object may not exist at this time, this does not point to anything.
Precautions for using static methods:
- Static methods cannot access non static members. However, non static members can access the of static members.
Note: the disadvantage of static is the limitation of access. The advantage is that it can be called directly by the class name.
- this and super keywords are not allowed in static methods.
The main() method is also static. Because main() is the entry of the program and is provided for the JVM. When you enter java XXX in dos, the JVM will start, and * * the JVM will load the class file named XXX into memory * *. And scan for the main() method. If there is a main() method, the JVM will call the main() method. When the JVM calls the main() method, it will not create an object. How to call a method without an object can only be statically modified. Called by the JVM through the class name.
4.4 static variables
Static can not only modify methods, but also modify member variables.
class Circle { //Radius of circle private double radius = 10; //PI. Because Pi is a fixed value, all objects share this data //It is not necessary to have this data in every object, so you can use static decoration static double pi = 3.14; //Constructor with parameters Circle(double radius) { this.radius = radius; } //Get circle area double getArea() { return radius * radius * pi; } } class CircleDemo { public static void main(String[] args) { System.out.println(new Circle(3).getArea()); } }
If the variable pi is not statically modified, when creating a Circle object, there will be a variable pi in each object, but pi is a fixed value. It is not necessary to have it in each object. At this time, you can statically modify this variable and let all objects share it.
4.5 differences between static variables and member variables
Differences between static variables and member variables:
- Variable belongs to different
The class to which a static variable belongs is also called a class variable.
The object to which a member variable belongs is also called an instance variable (object variable).
- Location in memory
Static variables are stored in the static area in the method area.
Member variables are stored in heap memory.
- Time in memory
Static variables are loaded with the loading of the class and disappear with the disappearance of the class.
Member variables appear in heap memory as the object is created and disappear as the object disappears.
4.6. Static loaded memory diagram
public class Person { //Person's name private String name; //All objects have nationality attribute and will CN. In this case, the member variable can be defined as static private static String country = "CN"; Person(String name) { this.name = name; } void showName() { System.out.println("name="+name); } //Static method static void showCountry() { System.out.println("Country="+country); } } class StaticDemo { public static void main(String[] args) { Person p = new Person("123"); p.showName(); //showCountry is a static method, which is called directly by the class name Person.showCountry(); } }
[the external chain picture transfer fails, and the source station may have anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-3d21uvck-160999059587) (D: \ lecturer work \ formal course \ lesson plan - final version \ phase I \ 5. Java - object-oriented \ img \ image-2020062716063506. PNG)]
Method area: it contains the only elements of the whole program, such as class and static. The constant pool is also in the method area.
4.7 static code block
Static code block, in fact, adds static keywords in front of the code block. This code block is called static code block.
It takes precedence over the execution of the main method and the construction code block. No matter how many objects are created, the static code block is executed only once, which can be used to assign values to static variables; Used to initialize a class.
public class Person { private String name; private int age; static{ System.out.println("Static code block executed"); } }
Application scenario of static code block: the class does not need to create an object, but needs to be initialized. At this time, part of the code can be stored in the static code block.
4.8. Construct code block & local code block
A normal code block is a code block defined directly in a method or statement:
class Demo{ public static void main(String[] args) { { int x = 1; System.out.println("Common code block" + x); } int x = 99; System.out.println("Outside the code block" + x); } } //result: //Common code block 1 //Outside the code block 99
Code blocks written directly in the class: take precedence over the execution of construction methods. Construction code blocks are used to initialize all objects. Construction code blocks will be executed every time an object is created. Constructor is used to initialize the specified object.
public class Person { private String name; private int age; static{ System.out.println("Static code block executed"); } { System.out.println("The construction code block is executed"); } Person(){ System.out.println("Person Parameterless constructor execution"); } Person(int age){ this.age = age; System.out.println("Person(age)Constructor execution of parameter"); } } class PersonDemo{ public static void main(String[] args) { Person p = new Person(); Person p1 = new Person(23); } }
Scope of variables in the code block: only valid in its own region (before and after {});
Block code: write code within a local block. Function: you can control the life cycle of local variables.
class Demo { public static void main(String[] args) { {//Local code block int x = 5; System.out.println(" Local code block..."+x); } System.out.println(" over..."); } }
4.9 object creation process
class Demo { static int x = 1; //Static member variable int y = 1; //Non static member variable static //Static code block { x = 2; System.out.println("static code...x="+x); } {//Construct code block System.out.println("cons code ...y="+y); } Demo() //Constructor { System.out.println("cons function ...y="+y); } } class CreateObjectTest { public static void main(String[] args) { Demo d = new Demo(); //Create a Demo object } }
Process summary of object loading:
- Load demo Class file into the method area and allocate space.
- If there are static variables, initialize by default and display the initialization value.
- If there is a static code block, execute it only once.
- Use the new keyword to open up space in the heap memory and specify the first address.
- Initialize the non static attribute in the object by default.
- Call the corresponding constructor for initialization.
- Inside the constructor.
- Call the superclass constructor super(); this() passively creates its parent class when a class is created.
- Display initialization of member variables.
- Construct code block initialization.
- Constructor content custom content initialization.
- After the object is initialized, assign the address to the d reference variable.
public class Demo2 { public static int k = 0; public static Demo2 t1 = new Demo2("t1"); public static Demo2 t2 = new Demo2("t2"); public static int i = print("i"); public static int j = print("j"); public static int n = 99; { print("constructor code"); } static { print("static code"); } public static int print(String s) { System.out.println("i="+i +" "+s+ " k=" + k + " n=" + n + " j=" + j); ++i; ++k; ++n; return i; } public Demo2(String string) { print(string); } public static void main(String[] args) { Demo2 d=new Demo2("T"); } }
4.10 scenario of singleton mode
The design pattern originated from the field of architecture. It is a set of summary of design experience that is repeatedly used and known by most people. Design patterns are used to be reusable, easier to be understood by others and ensure reliability.
Design pattern is an idea to solve a certain problem and an effective solution. Understand the problems they solve
Problem solved by the singleton: ensure the uniqueness of the object of a class in memory, that is, there is only one object of a class in memory.
Application scenario: when multiple programs are operating the same configuration file, program A needs to know the results after the operation. Program B needs to know and continue to operate based on the results after the operation of program A. On the premise that the data is stored in the configuration file object, it is required that the configuration file object operated by program A and program B is the same object.
To restrict other programs from creating objects of this class arbitrarily, ensure that there is only one object in memory.
To create an object, you need to call the constructor. As long as you privatize the constructor of this class and don't let other programs access it, other programs can't create an object. But when the private constructor is, other programs cannot create objects. If you need to use its object, you can create your own object in this class and provide external methods to obtain this class object.
4.11 code embodiment and minor problems of singleton mode
Hungry man model
public class Single { //Private constructor in this class private Single(){} //Create this type of object private static Single s = new Single(); //Provide external methods to obtain original objects public static Single getInstance(){ return s; } } Note: Unable to create due to external Single Object. If there is no object, it cannot be called getInstance Method, you need to getInstance Method is static, so that the outside world can call the method directly through the class name.
Lazy mode
public class Single { //private constructors private Single(){} //Create this class object in this class private static Single instance = null; //Provide external static access methods to obtain the instance object of this class public static Single getInstance(){ if(instance == null ) // There will be thread safety issues { instance = new Single(); } return instance; } } class SingleDemo { public static void main(String[] args) { //Gets the instance object s of the Single class Single s = Single.getInstance(); //Gets the instance object s2 of the Single class Single s2 = Single.getInstance(); System.out.println(s==s2); //true } }
4.12. Application of singleton mode
Lazy mode is characterized by * * the speed of obtaining objects at runtime is relatively slow, but it is relatively fast when loading classes * *. It only occupies resources in part of the whole application life cycle.
Hungry man mode, which is characterized by * * slow loading classes, but fast obtaining objects at runtime. It will occupy resources * * from loading to the end of the application.
These two modes have little performance difference for lightweight objects with fast initialization and less resources. There is no problem in choosing lazy or hungry. However, for heavyweight objects with slow initialization and high resource consumption, there will be obvious differences. Therefore, the application of hungry man mode to heavyweight objects is slow in class loading, but fast in runtime; Lazy mode, on the contrary, is fast when loading classes, but slow when getting objects for the first time at runtime.
From the perspective of user experience, we should first choose the hungry man mode. We are willing to wait for a program to take a long time to initialize, but we don't like to wait too long when the program is running, which gives people a feeling of slow response. Therefore, for the singleton mode with the participation of heavyweight objects, we recommend the hungry man mode.
//Describe Superman. class SuperMan { private String name; private static SuperMan man = new SuperMan("clarke"); private SuperMan(String name) { this.name = name; } public static SuperMan getInstance() { return man; } public void fly() { System.out.println(this.name +"..fly"); } } class SingeTest { public static void main(String[] args) { //superMan should be the only object. Ensure the uniqueness of superMan. It can be solved using singleton mode. //SuperMan man = new SuperMan("Clark"); SuperMan man1 = SuperMan.getInstance(); SuperMan man2 = SuperMan.getInstance(); man1.setName("hero"); man2.fly(); } }
5. Inherit
5.1. Introducing inheritance
class Student { String name; int age; void study() { System.out.println("study"); } } class Worker { String name; int age; void work() { System.out.println("work"); } }
Describe multiple things through code demonstration. Multiple things are found to have common attributes and behaviors. So the reusability of the code is very poor, so what should we do?
You can extract the same code and put it in a separate class.
class Student { void study() { System.out.println("study"); } } class Worker { void work() { System.out.println("work"); } } class Person { String name; int age; }
The code is extracted into the Person class, but the Student and Worker classes have nothing to do with the Person class. How can the Student and Worker classes use the name and age attributes in the Person class.
In order to have a relationship between classes, you need to use the inheritance mechanism provided in Java. The keyword extends is required for inheritance.
//Extract the commonalities of students and workers into the class of Person class Person { String name; int age; } //Students inherit Person through extensions, that is, Person is the parent class of Student class Student extends Person{ //Own unique methods in the student class public void study(){ System.out.println(name+"Students are learning...."); } } //Workers inherit Person through extensions, that is, Person is the parent class of workers class Worker extends Person{ //Unique methods among workers public void work(){ System.out.println(name+"The workers are working...."); } } //Test class public class Test{ public static void main(String[] args) { Student s = new Student(); s.name = "Xiao Ming"; s.study(); Worker w = new Worker(); w.name = "Zhang San"; w.work(); } }
Benefits of inheritance:
1. The emergence of inheritance improves the reusability of code and improves the efficiency of software development.
2. The emergence of inheritance makes the relationship between classes and provides the premise of polymorphism.
5.2. Single inheritance & multiple inheritance & multiple inheritance
Inheritance creates a relationship between classes. When do you use inheritance?
When using inheritance, we must ensure that there is a generic (b is a) relationship between classes, that is, xxx is one of zzz. For example, apples are a kind of fruit, and dogs are a kind of Canidae.
Java only supports single inheritance, not multiple inheritance. A class can only have one parent class and cannot have more than one parent class.
class SubDemo extends Demo{} //ok class SubDemo extends Demo1,Demo2...//error
Java supports multi-layer inheritance (inheritance system)
class A{} class B extends A{} class C extends B{}
When defining inheritance, you should pay attention to: do not inherit just to obtain a function in other classes.
Daily development skills:
In the inheritance system of multi-level inheritance, we usually look at the functions in the parent class, understand the basic functions of the system, and use the functions of the system by establishing subclass objects.
Although multi inheritance can make subclasses have the characteristics of multiple parent classes at the same time, its disadvantages are also very significant, mainly in two aspects:
- If there are instance variables with the same name in multiple parent classes inherited by a subclass, the subclass will have ambiguity when referring to the variable, and it is impossible to judge which parent class variable should be used.
- If you have the same method in multiple parent classes inherited by a subclass and whether the method is overwritten in the subclass, there will be ambiguity when calling the method, and it is impossible to judge which parent class method should be called.
5.3. Inheritance - Characteristics of member variables in child parent classes
Member variable: if a member variable with a different name appears in the parent class of a child class, there is no problem accessing it at this time.
class Fu { //Member variables in Fu. int num = 5; } class Zi extends Fu { //Member variables in Zi int num2 = 6; void show() { //Access num in parent class System.out.println("Fu num="+num); //Access num2 in subclasses System.out.println("Zi num2="+num2); } } class Demo { public static void main(String[] args) { Zi z = new Zi(); //Create subclass object z.show(); //Call the show method in the subclass } } //Code Description: the member variables in Fu class are non private and can be accessed directly in subclasses. If the member variables in Fu class are private, subclasses cannot be accessed directly.
When a member variable with the same name appears in the child parent class, you must use the super keyword to access the member variable in the parent class in the child class.
class Fu { //Member variables in Fu. int num = 5; } class Zi extends Fu { //Member variables in Zi int num = 6; void show() { //When a member variable with the same name appears in the child parent class //When you need to access non private member variables in the parent class in a subclass, you need to use the super keyword //Access num in parent class System.out.println("Fu num="+super.num); //Access num2 in subclasses System.out.println("Zi num2="+this.num); } } class Demo5 { public static void main(String[] args) { Zi z = new Zi(); //Create subclass object z.show(); //Call the show method in the subclass } }
Process resolution: while the subclass is created, the parent class is recorded in memory.
- When the program executes new Zi(); At this time, the Zi class bytecode file will be loaded, but since the Zi class inherits the Fu class, the * * parent class bytecode file * * needs to be loaded into the method area.
- When the bytecode of Zi and Fu is loaded. Execute new Zi(); That is, create Zi class objects in heap memory and allocate memory address 0x99 to them; After the memory space allocation of the object is completed, start the default initialization of member variables. At this time, it should be noted that the num of Fu will also be in this object.
- Then start the stack pressing of the zi constructor. There is an implicit super() statement in the * * zi constructor. At this time, the constructor of Fu will also stack. After the stack pressing of the constructor of Fu, the num of Fu will be displayed and initialized * *.
- Then * * Fu constructor pops the stack * *, executes the constructor of Zi, and the num of Zi displays initialization. Then the Zi constructor pops up the stack. At this point, the Zi object is created in the heap, and the memory address 0x99 is assigned to the z reference in the main() method. Then call Zi's show() method and press the stack with = = show() = = method.
Note: the usage of super is similar to this. This: represents the object reference of this class. Super: represents the memory space of the parent class, not the reference of the parent class.
The member variable with the same name in the child parent class is not used in development, because once the parent class completes the description of the attribute, the child class can use it directly.
5.4. Inheritance - Characteristics of member functions in child and parent classes - Rewriting & Application
When a method is called through an object in the program, it will first find out whether there is a corresponding method in the subclass. If there is a method in the subclass, it will execute the method in the subclass. If there is no method in the subclass, it will execute the corresponding method in the parent class. [principle of proximity]
class Fu{ public void show(){ System.out.println("Fu Class show Method execution"); } } class Zi extends Fu{ public void show2(){ System.out.println("Zi Class show2 Method execution"); } } public class Test{ public static void main(String[] args) { Zi z = new Zi(); z.show(); //There is no show method in the subclass, but the parent method can be found to execute z.show2(); } }
Member method special case - override
A subclass as like as two peas is exposed, which will result in overlay operations, also known as override rewriting, copying, or overwriting.
class Fu { void show() { System.out.println("Fu show"); } } class Zi extends Fu { //The subclass duplicates the show method of the parent class void show() { System.out.println("Zi show"); } }
Applications covered:
When the subclass needs the function of the parent class and the subclass of the function subject has its own unique content, you can copy the methods in the parent class. In this way, you not only follow the function of the parent class, but also define the unique content of the subclass.
For example: for example, when describing a mobile phone, it has the functions of sending text messages, making calls and displaying incoming call numbers. Later, because the mobile phone needs to add the display name and avatar in the incoming call display function, you can redefine a class to describe the mobile phone and continue the original class to describe the mobile phone. And override the caller ID function in the newly defined class, and add the function of displaying name and avatar.
public class Test { public static void main(String[] args) { new NewPhone().showNum(); } } class Phone{ public void sendMessage(){ System.out.println("send message"); } public void call(){ System.out.println("phone"); } public void showNum(){ System.out.println("Caller ID number"); } } class NewPhone extends Phone{ //Override the caller ID function of the parent class, and add its own function of displaying names and pictures public void showNum(){ //Call the function whose parent class already exists and use super super.showNum(); //Add your own unique function of displaying names and pictures System.out.println("Show caller name"); System.out.println("Show Faces "); } }
5.5 precautions for rewriting
Details of Rewriting:
1. If the subclass method overrides the parent method, you must ensure that the * * permission is greater than or equal to the parent permission * *.
class Fu() { void show(){} public void method(){} } class Zi() extends Fu { public void show(){} //There is no problem compiling and running void method(){} //Compilation error } // Public > Default > protected > private
2. Static can only override or be overridden by static.
3, write as like as two peas: the function of return type, function name, parameter list must be the same.
Summary: when a class is one of another (A is B), the function can be extended through inheritance. If the function content of the parent class needs special definition of the child class, override is used.
5.6 constructor features in child and parent classes (super())
When creating a subclass object, the constructor of the parent class will be executed first, because the first line of all constructors in the subclass has a default implicit super() statement. This (argument list) statement is used to call the constructor in this class, and super (argument list) is used to call the constructor in the parent class.
Why does * * subclass object initialization need to access the constructor in the parent class? Because the subclass inherits the content * * of the parent class, you must first see how the parent class initializes the content when creating an object.
public class Test { public static void main(String[] args) { new Zi(); } } class Fu{ int num ; Fu(){ System.out.println("Fu Constructor"+num); num = 4; } } class Zi extends Fu{ Zi(){ System.out.println("Zi Constructor"+num); } } // Execution result: // Fu constructor 0 // Zi constructor 4
Why does the constructor in a subclass have an implicit super()?
Reason: subclasses inherit the contents of the parent class, so * * when initializing a subclass * *, you must first perform the initialization of the parent class in the parent class. To make it easier to use the content in the parent class.
When * * there is no empty parameter constructor in the parent class * *, the constructor of the subclass must have a displayed super() statement to specify the constructor in the parent class to be accessed.
class Fu extends Object { Fu() { //super(); //Display initialization. System.out.println("fu constructor run..A.."); } Fu(int x) { //Display initialization. System.out.println("fu constructor run..B.."+x); } } class Zi extends Fu { Zi() { //super(); System.out.println("zi constructor run..C.."); } Zi(int x) { super(); System.out.println("zi constructor run..D.."+x); } } class Demo { public static void main(String[] args) { new Zi(); new Zi(3); } }
5.7 details of subclass instantiation process
If this is written in the first line of the constructor of the subclass and other constructors of this class are called, there is no statement of super calling the parent class, because this() or super() can only be defined in the first line of the constructor, because the initialization action must be executed first.
There is also an implicit super() in the parent constructor. Remember: as long as it is a constructor, the first line is super() by default; In the design of Java system, a parent class Object of all objects is defined.
be careful:
The constructor in the class has * * implicit super() statement on the first line by default. When accessing the constructor in the parent class. Therefore, the constructor of the parent class can initialize * * for its own object and can initialize * * for its own subclass object. If the default implicit super () statement does not have a corresponding constructor, you must explicitly call the constructor in the * * constructor in the form of this or super**
public class Demo06 { public static void main(String[] args) { Zi3 zi3 = new Zi3(7); zi3.show(); } } class Fu3 { public int num = 3; public Fu3(int num) { System.out.println("adopt Fu3(int num)Complete initialization."); this.num = num; } } class Zi3 extends Fu3{ public Zi3(){ this(5); } public Zi3(int num){ // super() super(num); } public void show(){ System.out.println(num); } }
5.8. Super application
Exercise: describe the two classes of students and workers, extract their common name and age and store them in the parent class, and provide the corresponding get and set methods. At the same time, the name and age must be clear when creating student and worker objects.
class Person{ private int age; private String name; 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; } } class Student extends Person { // Constructor of Student class Student(String name, int age) { // Use the super keyword to call the parent class constructor and perform the corresponding initialization action super(name, age); } public void study() {// Unique methods in Studnet System.out.println(this.getName() + "Students are studying"); } } class Worker extends Person { Worker(String name, int age) { // Use the super keyword to call the parent class constructor and perform the corresponding initialization action super(name, age); } public void work() {// Unique methods in Worker System.out.println(this.getName() + "The workers are working"); } } public class Test { public static void main(String[] args) { new Student("Xiao Ming",23).study(); new Worker("petty thief",45).work(); } }
5.9. final keyword
The emergence of inheritance improves the reusability of code and facilitates development. However, there are also problems. Some classes do not want to be inherited after being described, or some methods and functions of some classes are fixed, and subclasses cannot be overridden. However, when subclasses inherit these special classes, they can override the methods in them.
To solve these problems, we need to use a keyword final, which means final and immutable. Final is a modifier that modifies classes, class members, and local variables.
The final modifier class cannot be inherited, but it can inherit other classes.
Final modified methods cannot be overwritten, but there are no final modified methods in the parent class. Final can be added after the child class is overwritten.
Variables modified by final are called constants. These variables can only be assigned once. They must have initial values and cannot be changed when they are defined.
The reference type variable modified by final indicates that the reference of the reference variable cannot be changed, rather than the data in the object to which the reference refers can still be changed.
When a * * data in the program is fixed, in order to increase readability, you can name the data. In order to ensure that the value of this variable is not modified, add the final modifier * *, and the variable becomes a constant with strong readability. The writing specification is that all * * letters of constant names modified by final are capitalized. If it is composed of multiple words, the words pass through each other_ connect.
In general specification: all letters of constant name are capitalized. If there are multiple words, underline is used between words. public static final Modified constants are called global constants; public static final double PI = 3.14159265358979323846; public static final String APP_SEPARATOR = "/";
5.10 abstract classes - generation & Features & details
When writing a class, we often define some methods for the class. These methods are used to describe the behavior of the class. Then these methods have specific method bodies.
Method body: after the method {} and its code, it represents the specific execution operation of the method.
But sometimes, a parent class only knows what methods the subclass should contain, but it can't know exactly how the subclass implements these methods. For example, a graphic class should have a method for calculating the perimeter, but the algorithm for calculating the perimeter of different graphics is different.
When analyzing things and finding common content, upward extraction occurs. There is a special case that * * function declarations are the same and function subjects are different. You can also extract * * at this time, but only the method declaration, not the method body. Then this method is an abstract method.
Description: dog behavior: barking.
Description: wolf behavior: roar.
Dogs and wolves have something in common, which can be extracted upward. Extract their common type * *: Canidae. Because both dogs and wolves have the function of roaring, but how they roar is different. At this time, when describing the canine family, we found that some = = functions (roar) = = are not specific. These non specific functions need to be identified in the class through the keyword abstract in java.
When an abstract function is defined, the class must also be modified by the abstract keyword. The class modified by the abstract keyword is an abstract class.
abstract class Canidae { abstract void Roar();//abstract functions. Need abstract modification and semicolon; end } class Dog extends Canidae { void Roar() { System.out.println("Woof, woof, woof"); } } class Wolf extends Canidae { void Roar() { System.out.println("Ow, ow, Ow"); } }
Abstract class features:
1. Abstract classes and abstract methods need to be modified by abstract. Abstract methods must be * * defined in abstract classes * *.
2. Abstract classes cannot create instances. Reason: calling abstract methods is meaningless.
3. Only when all the abstract methods in the abstract class are covered can its subclasses be instantiated. Otherwise, the subclass is still an abstract class.
The reason why inheritance is more in the thought is that in the face of common types, the operation will be simpler.
Details:
1. Abstract class must be a parent class?
Yes, because it comes from continuous extraction.
2. Does the abstract class have a constructor?
Yes, although you can't initialize your own objects, you can initialize your own subclass objects.
Similarities and differences between abstract classes and general classes:
Same:
1. They are all used to describe things.
2. Attributes and behaviors can be defined among them.
Different:
1. General * * class can specifically describe things. Abstract classes describe things without concrete information**
2. One more member can be defined in the abstract class: abstract function.
3. General classes can create objects, while abstract classes must not create objects.
3. Whether abstract methods can not be defined in abstract classes.
Yes, what is the significance of the existence of this abstract class? Just don't let this class create objects.
4. What keywords cannot abstract coexist with?
1. final: the class modified by fianl cannot be inherited, while the class modified by abstract must have subclasses. final modified methods cannot be overridden, but abstract modified methods must be implemented by subclasses.
2. Static: the method modified by static belongs to a class. It exists in the static area and has nothing to do with the object. The abstract method has no method body, and it makes no sense to call it with a class name.
3. Private: the subclass of private method cannot inherit, and there is no coverage. abstract and private use the modification method together. abstract requires the subclass to implement this method, while the private modification subclass cannot get the parent method at all, which is contradictory to each other.
6. Abstract class & & Interface
Requirements: programmers in the company have name, job number, salary and work content.
In addition to the name, job number, salary, bonus and work content of the project manager. Data modeling of given requirements.
programmer:
Attributes: name, job number, salary
Behavior: work
Project Manager:
Attributes: name, job number, salary, bonus
Behavior: work
The analysis found that there should be a relationship between programmers and project managers. Their commonness can be extracted upward to the commonness type: employees.
Employees:
Attributes: name, job number, salary
Behavior: work
It is found that the work content of employees is not specific. It should be abstract and embodied by specific subclasses.
abstract class Employee { private String name; private String id; private double pay; //When constructing an employee object, it has three properties as soon as it is initialized. public Employee(String name,String id,double pay) { this.name = name; this.id = id; this.pay = pay; } //Work behavior is described by abstract classes because the work content is not specific public abstract void work(); } //Specific subclass: programmer. class Programmer extends Employee { public Programmer(String name,String id,double pay) { super(name,id,pay); } public void work() { System.out.println("code...."); } } //Specific sub category: manager. class Manager extends Employee { //Unique properties. private double bonus; public Manager(String name,String id,double pay,double bonus) { super(name,id,pay); this.bonus = bonus; } public void work() { System.out.println("manage"); } }
6.1 interface - Definition & Implementation
When all methods in an abstract class are abstract methods, the * * abstract class can use the mechanism of interface to embody * *.
How is the interface defined? The class keyword can be used to define ordinary or abstract classes, and the interface definition must be completed with the interface keyword.
Before 1.8, it can be said that interfaces are extremely abstract classes, which are full of abstract methods. After 1.8, there will also be non abstract methods in abstract classes. We distinguish between the two from the perspective of design. If we need to use specific properties and methods, we use abstract classes, and in other cases, we use interfaces.
interface Demo { abstract void show1(); abstract void show2(); } //Only constants can be defined in the interface
Characteristics of members in the interface:
1. Variables can be defined in the interface, but they must be decorated with fixed modifiers. Therefore, variables in the interface are also called * * constants * *.
2. Methods can be defined in the interface, and methods also have fixed modifiers, public abstract.
3. All members in the interface are public.
4. Interface cannot create object.
5. Subclasses can only be instantiated after they cover all the abstract methods in the interface. Otherwise, the subclass is an abstract class.
Interfaces (all abstract methods before 1.8) – abstract classes (partial abstract methods) – classes (no abstract methods)
interface Demo//Define an interface named Demo. { public static final int NUM = 3; public abstract void show1(); public abstract void show2(); } //Define subclasses to override methods in the interface. Subclasses must have a relationship with interfaces. The relationship between classes is inheritance, and the relationship between classes and interfaces is implementation. By keyword implements class DemoImpl implements Demo//Subclasses implement the Demo interface. { //Override methods in the interface. public void show1(){} public void show2(){} }
6.2 interface - Multi implementation
**The most important embodiment of the interface: * * solve the disadvantages of multiple inheritance. The multi inheritance mechanism is implemented in java.
interface A { void abstract show1(); } interface B { void abstract show2(); } class C implements A,B// Multiple implementations. Implement multiple interfaces at the same time. { public void show1(){} public void show2(){} }
Solve the disadvantages of multiple inheritance
Disadvantages: in case of multiple inheritance, when multiple parent classes have the same function, the subclass call will produce uncertainty.
In fact, the core reason is that the function in the multi inheritance parent class has a subject, which leads to the uncertainty of which subject content to run when calling the runtime.
In multi implementation, because the functions in the interface have no method body, it is determined by subclasses, and the source is the implementation class that implements them.
6.3. The subclass inherits the class and implements the interface at the same time
Subclasses extend functions by inheriting the parent class. The functions extended by inheritance are the basic functions that subclasses should have. What if the subclass wants to continue to expand the functions in other classes? This is done by implementing the interface.
class Fu { public void show(){} } interface Inter { public abstract void show1(); } class Zi extends Fu implements Inter { public void show1() {} }
6.4 multi inheritance of interfaces
Extensions can be used for inheritance between multiple interfaces.
interface A{ abstract void show(); } interface B{ abstract void show1(); } interface C{ abstract void show2(); } interface D extends A,B,C{ abstract void show3(); }
In development, if the same methods exist in multiple interfaces, then if a class implements these interfaces, it is necessary to implement the methods in all interfaces. Since the methods in the interface are abstract methods, the uncertainty of calling will not occur after the subclass is implemented.
6.5 origin of abstract classes without abstract methods
In development, if there are multiple abstract methods in an interface, but only some of them are used to implement this interface, we still need to implement other methods that are not used. This obviously does not meet our requirements, but we can't do without implementing these methods. So what? You can use an abstract class as a transition, and this abstract class implements this interface, and all methods exist as empty implementations. This is the existence value of abstract classes without abstract methods. We just need to inherit this abstract class and override the methods we need to use.
//Interface with multiple methods interface Inter{ abstract void show(); abstract void show1(); abstract void show2(); abstract void show3(); } //As an excessive abstract class, this class implements all methods of the interface, and the implementation here is an empty implementation abstract class AbsInter implements Inter{ public void show(){} public void show1(){} public void show2(){} public void show3(){} } /* //This class implements Inter directly, but only uses other show and show2 methods, which leads to the implementation of the other two methods //It doesn't meet our requirements class SubInter2 implements Inter{ public void show() { System.out.println("show"); } public void show1() { } public void show2() { System.out.println("show2"); } public void show3() { } } */ //This class only uses the show and show2 methods in the interface, as long as it overrides show and show2 in the abstract class class SubInter extends AbsInter{ public void show(){ System.out.println("show"); } public void show2(){ System.out.println("show2") } }
7. Interface
7.1 interface idea
I learned the code embodiment of the interface. Now let's learn the idea of the interface. Next, I will explain it from examples in life.
For example: we all know that there are many sockets on the computer, and these sockets can be inserted into the corresponding devices. Why can these devices be inserted on it? The main reason is that these devices comply with the use rules of this socket during production, otherwise they will not be able to be inserted into the interface, let alone used. The discovery of this socket allows us to use more devices.
Summarize the benefits of interface in development:
1. The appearance of interface expands the function.
2. Interfaces are actually exposed rules.
3. The appearance of interface reduces the coupling, that is, the decoupling between devices is realized.
The appearance of the interface is convenient for later use and maintenance. One party is using the interface (such as computer) and the other party is implementing the interface (equipment plugged into the socket). For example: notebook uses this rule (Interface), and computer peripherals implement this rule (Interface).
7.2 differences between abstract and abstract interfaces
Analyze and demonstrate the usage of abstract classes and interfaces through examples.
Abstract classes are like the induction and summary of existing things, and their attributes and behaviors are developed and used in subsequent subclasses. The interface is like a kind of separation. The subsequent implementation is a supplementary description of it. It only defines rules. One congenital, one acquired
7.2.1. Examples:
Dog: Behavior: Roar; having dinner; Sniffer Dog: Behavior: Roar; having dinner; Anti drug;
7.2.2 thinking:
Because dogs are divided into many kinds, their way of roaring and eating is different. They can't be concretized when describing, that is, when the behavior of roaring and eating can't be clearly described, the specific action of the behavior can't be clearly defined. This behavior can be written as abstract behavior, so this class is also abstract class.
However, when the dog has other additional functions, this function is not in the system of this thing. At this time, the dog can not only have its own characteristics of canine, but also have other additional functions, which can be defined in the interface.
interface Anti drug{ abstract void Anti drug(); } //Define the common functions of this reminder in Canidae abstract class Canidae{ abstract void having dinner(); abstract void Roar(); } // A dog of the family Canidae that inherits the characteristics of a dog of the family Canidae, //Since the anti drug dog has the anti drug function, it only needs to realize the anti drug interface, so as to ensure that the anti drug dog has the characteristics of canine and the anti drug function class Sniffer Dog extends Canidae implements Anti drug{ public void Anti drug() { } void having dinner() { } void Roar() { } } class Anti drug pig implements Anti drug{ public void Anti drug() { } }
7.2.3 summarize the differences between interfaces and abstract classes through the above examples
Similarities:
-
Are at the top of inheritance and used to be implemented or inherited by others;
-
Cannot be instantiated;
-
Both contain abstract methods, and their subclasses must override these abstract methods;
difference:
-
Abstract classes provide implementations for some methods, avoid subclasses implementing these methods repeatedly, and provide code reusability; Interfaces can only contain abstract methods and extremely abstract classes;
-
A class can only inherit one direct parent class (possibly an abstract class), but can implement multiple interfaces; Interface makes up for the deficiency of Java single inheritance.
Selection of both:
- Give priority to interfaces and try to use less abstract classes;
- Abstract classes are selected when it is necessary to define the behavior of subclasses and provide common functions for subclasses;
8. Polymorphism
8.1 polymorphism - benefit & disadvantage & premise
First, we introduce polymorphism through code.
//Describe the dog. The dog has the behavior of eating and guarding the house class Dog { public void eat() { System.out.println("Gnaw a bone"); } public void lookHome() { System.out.println("Housekeeping"); } } //Describe the cat. The cat has the behavior of eating and catching mice class Cat { public void eat() { System.out.println("Eat fish"); } public void catchMouse() { System.out.println("Catch a mouse"); } } class DuoTaiDemo { public static void main(String[] args) { /*There are multiple dog and cat objects that need to call the behavior of eating This will result in d.eat(); Code repeatability is very serious Dog d = new Dog(); d.eat(); In order to improve the reusability of code, d.eat(); Code encapsulation public static void method(Dog d) { d.eat(); } Then create an object and directly call the method method method method(new Dog()); method(new Dog()); However, when creating a Cat object, you also need to call the eat method, which can also be encapsulated public static void method(Cat c) { c.eat(); } */ } }
Later, when there is a pig object, it is also necessary to encapsulate the = = eat() = = method. When each more animal has to define the function separately, * * the encapsulation method allows the animal object to do things, and you will find that the code has poor scalability** How to improve the extensibility of the code? It is found that since animals are allowed to eat, whether dog or cat, eat is their common character, then eat is extracted and extracted into the parent class.
abstract class Animal { //Because the eat mode of each small animal is different, the specific behavior of eat cannot be accurately described in the parent class //Therefore, it can only be described by abstract methods, resulting in this class also being an abstract class abstract public void eat(); }
When there is an Animal abstract class, dogs and cats only need to inherit this class and implement their unique eat method.
//Describe the dog. The dog has the behavior of eating and guarding the house class Dog extends Animal { public void eat() { System.out.println("Gnaw a bone"); } public void lookHome() { System.out.println("Housekeeping"); } } //Describe the cat. The cat has the behavior of eating and catching mice class Cat extends Animal { public void eat() { System.out.println("Eat fish"); } public void catchMouse() { System.out.println("Catch a mouse"); } }
Since Dog is a kind of Animal and Cat is also a kind of Animal, you don't have to face specific animals, but just face Animal.
Dog d = new Dog(); Animal a = new Dog(); Cat c = new Cat(); Animal aa = new Cat();
Through the above code, it is found that Animal type can accept both Dog type and Cat type. When animals do things again, they don't have to face specific animals, but just face Animal. Therefore, the above method can be modified to:
// polymorphic public static void method(Animal a) { a.eat(); }
method(Animal a) can accept all small animals of the subtype of Animal, and the method method does not care about which type it is. That is, you can receive all Dog and Cat objects and let them eat by creating a reference to Animal. Thus, the expansibility of the program is improved.
Embodiment of polymorphism:
The reference of the parent class or interface points to its own subclass object.
Dog d = new Dog();//The type of Dog object is Dog type. Animal a = new Dog();//The type of Dog object is Dog type on the right and Animal type on the left.
Benefits of polymorphism:
The expansibility of the program is improved.
Disadvantages of polymorphism:
When operating a subclass object through a parent class reference, only the existing methods in the parent class can be used, and the methods unique to the subclass cannot be operated.
The premise of polymorphism:
- There must be relationships: inheritance, implementation.
- There are usually rewriting operations.
8.2 polymorphism transformation
When the reference of the parent class points to the subclass object, an upward transformation occurs, that is, the subclass type object is transformed into the parent type. The advantage of upward transformation is to hide the subclass types and improve the scalability of the code.
However, the upward transformation also has disadvantages. It can only use the common contents of the parent class, but can not use the unique functions of the child class, and the functions are limited.
//Describe the commonness of animals eat abstract class Animal{ abstract void eat(); } //Describe things like dog class Dog extends Animal{ void eat(){ System.out.println("Gnaw a bone"); } void lookHome(){ System.out.println("Housekeeping"); } } //Describe kittens class Cat extends Animal{ void eat(){ System.out.println("Eat fish"); } void catchMouse(){ System.out.println("Catch a mouse"); } } // Test class public class Test { public static void main(String[] args) { Animal a = new Dog(); //Polymorphism is formed here a.eat(); //a.lookHome();// Using Dog's unique method requires downward transformation Dog d = (Dog)a; d.lookHome(); Animal a1 = new Cat(); a1.eat(); /** * Since a1 specifically refers to an instance of Cat rather than a Dog instance, a1 is forcibly converted to a Dog type, * Will happen ClassCastException is an exception. You need to make a robustness judgment before turning. if(!Dog instanceof a1){ // Judge whether the current object is of Dog type System.out.println("Type mismatch, cannot convert '); return;// Method execution aborted } Dog d1 = (Dog)a1; d1.catchMouse(); */ } }
Upward Transformation:
When you do not need to face the subclass type, you can complete the corresponding operation by improving the extensibility or using the function of the parent class. At this time, you can use the upward transformation.
Downward Transformation:
When you want to use subclass specific functions, you need to use downward transformation
Benefit: subclass specific functions can be used.
Disadvantages: need to face specific subclass objects; ClassCastException type conversion exceptions are easy to occur during downward transformation. Type judgment must be made before conversion.
8.3 polymorphism - Examples
/* Describe Mr. Bi and grandpa Bi, Mr. Bi has the functions of giving lectures and watching movies Grandpa Bi has the functions of lecturing and fishing */ class bisu { void lecture(){ System.out.println("Politics"); } void go fishing(){ System.out.println("go fishing"); } } //Teacher Bi inherited grandpa Bi's functions of lecturing and fishing, //However, the contents of Mr. Bi and grandpa Bi's lectures are different, so Mr. Bi should cover grandpa Bi's lecture function class Miss Bi extends bisu { void lecture(){ System.out.println("Java"); } void watch movie(){ System.out.println("watch movie"); } } // test public class Test { public static void main(String[] args) { //Polymorphic form bisu a = new Miss Bi(); //Upward transformation a.lecture(); // In fact, it is the teacher's function to finish the lecture a.go fishing(); // Grandpa Bi appears here, but the object is actually teacher Bi, and teacher Bi inherits grandpa Bi, that is, teacher Bi also has specific fishing functions // When you want to call Mr. Bi's unique movie watching function, you must carry out type conversion Miss Bi b = (Miss Bi)a; //Downward transformation b.watch movie(); } }
When you need to use the specific methods of subclasses, you need to use the down conversion type name = (conversion type) object, which is similar to forced type conversion.
Conclusion: in the process of transformation, only teacher Bi's object is undergoing type conversion from beginning to end, and the parent object cannot be converted into a child object.
public class Demo02 { public static void main(String[] args) { Old Master old = new Little sir("Xiao He",23); old.Preach(); old.Teach(); Little sir little = (Little sir)old; little.Dispel doubts(); } } class Old Master{ private String name; private int age; public Old Master(String name,int age){ this.name = name; this.age = age; } public void Preach(){ System.out.println("Cultivate one's moral integrity, govern the country and level the world!!!"); } public void Teach(){ System.out.println("Ceremony, music, shooting, imperial, calligraphy, number"); } } class Little sir extends Old Master{ public Little sir(String name,int age){ super(name, age); } public void Teach(){ System.out.println("My ancestors used to teach six arts, but now I'm talking about it Java..."); } public void Dispel doubts() { System.out.println("Remain true to our original aspiration!!!"); } }
Polymorphism - Practice - laptop
Requirements:
- Phase 1: use the notebook. The notebook has a running function, and the notebook object is required to run this function.
- Phase 2: if you want to use a mouse, you have another function to use the mouse and add a mouse object.
- Stage 3: if you want to use a keyboard, you have to use one more keyboard function and one more object.
- Problem: for each additional function, a function needs to be defined in the notebook object, and the program scalability is very poor.
/** * Description notebook, notebook using USB mouse, USB keyboard * Define the USB interface. The notebook should use the USB device, that is, the notebook needs to reserve the USB interface that can be inserted into the USB device during production, that is, the notebook has the ability to * Use the function of USB device, but the notebook doesn't care about what USB device is. As long as it meets the USB specification, it can. * If the mouse and keyboard can be used on the computer, the mouse and keyboard must also comply with the USB specification, otherwise the mouse and keyboard cannot be used after production. */ //Define the rules that should be observed among mouse, keyboard and notebook interface USB{ void open();//Turn on function void close();//Turn off function } //USB rules for mouse implementation class Mouse implements USB{ public void open(){ System.out.println("Mouse on"); } public void close(){ System.out.println("Mouse off"); } } //Keyboard implementation USB rules class KeyBoard implements USB{ public void open(){ System.out.println("Keyboard on"); } public void close(){ System.out.println("Keyboard off"); } } // Define notebook class NoteBook{ //Notebook on operation function public void run(){ System.out.println("Notebook operation"); } //The notebook uses USB device. When the notebook entity calls this function, it must pass a USB device that conforms to USB rules public void useUSB(USB usb){ //Determine whether there is a USB device if(usb != null){ usb.open(); usb.close(); } } public void shutDown(){ System.out.println("Notebook off"); } } public class Test { public static void main(String[] args) { //Create a notebook entity object NoteBook nb = new NoteBook(); //Create a mouse entity object Mouse m = new Mouse(); //Create a keyboard entity object KeyBoard kb = new KeyBoard(); //Notebook on nb.run(); //Notebook use mouse nb.useUSB(m); //Notebook keyboard nb.useUSB(kb); //Notebook off nb.shutDown(); } }
8.4 polymorphism - Characteristics of members
The occurrence of polymorphism will lead to slight changes in the member variables in the child parent class. The following code is shown:
class Fu { int num = 4; } class Zi extends Fu { int num = 5; } public class Demo { public static void main(String[] args) { Fu f = new Zi(); System.out.println(f.num); Zi z = new Zi(); System.out.println(z.num); } }
Polymorphic member variables:
When a member variable with the same name appears in the child parent class, when calling the variable:
Compile time: refers to whether there are called member variables in the parent class of the class. No, compilation failed.
Runtime: refers to the value of the member variable in the parent class of the class to which it belongs.
Simple note: both compilation and operation refer to the left side of the equal sign. Compile and run. Look at the left.
class Fu2 { int num = 4; void show() { System.out.println("Fu2 show num"); } } class Zi2 extends Fu2 { int num = 5; void show() { System.out.println("Zi2 show num"); } } class Demo2 { public static void main(String[] args) { Fu f = new Zi(); f.show(); } }
Polymorphic member functions:
Compilation time: if there is no function to be called in the parent class of the reference subclass object, the compilation fails.
Runtime: whether the reference subclass overrides the method and runs the member function of the subclass object.
In short: compile to the left and run to the right.
class Fu3 { int num = 4; static void method() { System.out.println("fu3 static method run"); } } class Zi3 extends Fu3 { int num = 5; static void method() { System.out.println("zi3 static method run"); } } class Demo3 { public static void main(String[] args) { Fu3 f = new Zi3(); f.method(); } }
Static polymorphic function:
Polymorphic call: both compilation and operation refer to the static function in the class to which the reference type variable belongs.
In short: compile and run to the left of the equal sign. In fact, you don't need objects to call static methods. Static methods are called directly through classes.
Conclusion:
- For member variables and static functions, the compilation and operation are shown on the left.
- For member functions, compile to the left and run to the right.
Thinking question 1
class Fu{ int num = 5; void show(){ System.out.println("Fu show "+num);// this.num } } class Zi extends Fu{ int num = 6; } public class Test { public static void main(String[] args) { Fu f = new Zi(); f.show(); } } //What is the result? 5
Question 2
class Fu{ int num = 5; void show(){ System.out.println("Fu show "+this.num); } } class Zi extends Fu{ int num = 6; void show(){ System.out.println("Zi show "+num); } } public class Test { public static void main(String[] args) { Fu f = new Zi(); f.show(); } } //What is the result? 6
9. Object overview
The Object class is the root class in the Java language, that is, the parent class of all classes. All method subclasses described in it can be used. When an Object is instantiated, the final parent class is Object.
The Object class in JAVA API describes the methods common to all objects.
[the transfer of external chain pictures fails, and the source station may have anti-theft chain mechanism. It is recommended to save the pictures and upload them directly (img-di5jvcsc-1609990592) (D: \ lecturer work \ formal course \ phase I \ course notes \ day 7 \ image-20200711081631620.png)]
There is Src in JDK Zip file, which is the source file of all Java classes. You can view the source code of the corresponding class.
9.1 introduction to common in Object class
9.1.1. equals method
The equals method is used to compare whether two objects are the same. In fact, it uses the memory address of the Object for comparison. The equals method in the Object class uses the = = comparison operator internally.
To compare whether two objects are the same in development, they are often compared according to the unique data in the object, that is, in development, it is often necessary to copy the equals method to compare according to the unique data of the object.
/* * Describe the class of people and define the function to judge whether they are peers according to their age * Because you want to compare according to the unique data of the specified class, you just need to override the equals method in the Object * Compare in the method body according to the unique data of the class */ class Person extends Object{ int age ; //Duplicate the equals method of the parent class to realize its own comparison method public boolean equals(Object obj) { //Determine whether the object that currently calls the equals method is the same as the object being passed in. if(this == obj){ return true; } //Judge whether the object passed in is of type Person if(!(obj instanceof Person)){ return false; } //Transform obj downward into a Perosn reference and call its unique data Person p = (Person)obj; return this.age == p.age; } }
Note: when copying the equals method in Object, you must note that the parameter = = public boolean equals(Object obj) = = is the Object type. When calling Object specific data, you must carry out type conversion, and you must judge the type before conversion.
9.1.2 toString method
==The toString() = = method returns the string representation of the object, which is actually the type + @ + hash value of the object
Since the result returned by the * * toString() method is the memory address * *, it is often necessary to get the corresponding representation according to the specific data of the object in development, so it is also necessary to rewrite the toString method.
class Person extends Object{ int age ; //Copy the toString method according to the unique data of the Person class public String toString() { return "Person [age=" + age + "]"; } }