1 object oriented
1.1 concept
Object oriented is a software development method and a programming paradigm. The concept and application of object-oriented have gone beyond program design and software development, and extended to fields such as database system, interactive interface, application structure, application platform, distributed system, network management structure, CAD technology, artificial intelligence and so on. 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.
Object oriented programming is a programming idea in line with human thinking habits. In real life, there are all kinds of things in different forms, and there are all kinds of connections between these things. In the program, objects are used to map real things, and the relationship between objects is used to describe the relationship between things. This idea is object-oriented.
1.1.1 distinction between object-oriented and process oriented
Object oriented: object oriented is to divide the transaction constituting the problem into multiple independent objects according to certain rules, and then solve the problem by calling the object method.
For example, for a cooked meal, no matter who makes the meal, he can eat it (in short, skip the steps to get the results directly)
Process oriented: process oriented is to analyze the steps needed to solve the problem, and then use functions to implement these steps one by one, and call them in turn when using.
For example, put the elephant in the refrigerator
- Open the refrigerator door first
- Put the elephant in
- Close the refrigerator door
1.2 three characteristics of object-oriented
1.2.1 packaging
Encapsulation is the core idea of object-oriented. It encapsulates the attributes and behaviors of objects without letting the outside world know the specific implementation details, and encapsulates the relevant data into a "class" component
1.2.2 succession
Inheritance mainly describes the relationship between classes. Through inheritance, the functions of the original class can be extended without rewriting the original class.
1.2.3 polymorphism
Polymorphism means that after the attributes and functions defined in a class are inherited by other classes, when the subclass object is directly assigned to the parent class reference variable, variables of the same reference type call the same method, showing a variety of different behavior characteristics.
2 classes and objects
Type 2.1
- The most basic unit of the Java language is the class, which is similar to the type.
- A class is an abstraction of a class of things.
- It can be understood as template or design drawing.
Abstract concept: a class is an abstract description of a class of things, and objects are used to represent the individuals of such things in reality.
2.2 object
Each object has three characteristics: object state, object behavior and object identification.
- The state of an object is used to describe the basic characteristics of an object.
- The behavior of an object is used to describe the function of an object.
- Object identification means that objects have a unique address value in memory to distinguish them from other objects.
- A class is an abstraction of a class of things, and an object is a concrete implementation.
2.3 relationship between class and object
Analysis: people in the figure above can be regarded as a class, and each specific person (such as Xiaohan, Xiaoshi, etc.) can be regarded as an object. The relationship between classes and objects can be seen from the relationship between people and specific individuals.
Description: class is used to describe the common characteristics of multiple objects. It is the template of the object. Object is used to describe individuals in reality. It is an instance of the class. An object is a materialization of a class, and a class can correspond to multiple objects
2.3.1 object oriented case exercise
public class TestCreateClass { public static void main(String[] args) { /** * Create an object of the corresponding class through the new key, * Use the object's resources through */ Phone p = new Phone(); p.call(); p.message(); p.video(); System.out.println(p.brand); System.out.println(p.color); System.out.println(p.size); System.out.println(p.price); System.out.println("************************************"); Phone p2 = new Phone(); p2.brand = "Huawei"; p2.color = "rose gold"; p2.size = 5.6; p2.price = 4999.99; System.out.println(p2.brand); System.out.println(p2.color); System.out.println(p2.size); System.out.println(p2.price); p2.call(); p2.message(); p2.message(); } } /**Encapsulation: encapsulate the characteristics and behaviors of a class of things into a class component*/ class Phone { // 1. Define phone features /** Attributes: described by member variables */ String brand; // brand String color; // colour double size; // size double price; // Price // 2. Define phone features /** Describe by method */ public void call() { System.out.println("Pretend to be on the phone...."); } public void message() { System.out.println("Pretend to be texting"); } public void video() { System.out.println("Are you really watching the live broadcast"); } }
3 storage of objects in memory
Java divides memory into five areas, and we focus on stack and heap.
- Generally speaking, local variables exist in the stack, and the memory is released after the method is executed
- Objects (things from new) are stored in the heap. Memory will be released only when the objects are no longer used
- Each heap memory element has an address value
- All properties in the object have default values
TIPS: stack and queue refers to a data structure.
Stack: FILO – First In Last Out
Queue: FIFO – First In First Out
3.1 packaging
3.1.1 general
Encapsulation is the core idea of object-oriented. It encapsulates the attributes and behaviors of objects without letting the outside world know the specific implementation details, and encapsulates the relevant data into a "class" component
effect:
- Improve security
- Improve reusability
3.1.2 private keyword
Private (current class access level): if a member of a class is modified by a private access controller, the member can only be accessed by other members of the class, and other classes cannot access it directly. Class is well encapsulated through the private keyword. Can be used to modify member variables and member methods. Privatized members can only be accessed in this class
3.1.3 sub packaging case exercise 1
package cn.tedu.oop; /*This class is used to test the necessity of encapsulation*/ public class TestPrivate1 { public static void main(String[] args) { //5. Create objects for testing User u = new User(); u.name = "ximen qing"; System.out.println(u.name); //The attribute needs to be encapsulated. If it is not encapsulated, you can directly modify the value of the attribute //It doesn't need to be operated in the way we set in advance //u.money = 1000000; //System.out.println(u.money); u.setMoney(109999); System.out.println(u.queryMoney()); } } //1. Create a User class User class User{ //2. Define the attributes of the user class public String name; private double money = 10000; //3. Provide method 1: it can be used to query the balance of the current account public double queryMoney(){ /*Permission verification can be added later*/ return money; } //4. Provide method 2: you can set the balance of the current account public void setMoney(double money){ /*Permission verification can be added later*/ this.money = money; } }
3.1.4 packaging case exercise 2
/** * 1,A pair of classes can be created in the java file, but only one class modified by public can be created * And the name of this java file must be consistent with the name of this public class */ /** * Summary: * 1,Encapsulation of attributes: private keywords are used -- public get and set methods are provided, and external methods are provided to obtain / set attribute values * 2,Method encapsulation: use the private keyword -- call this private method in the public method of this class */ public class TestPrivate { public static void main(String[] args) { Student s = new Student(); s.name = "Zixia"; s.sno = 5; //s.subject = "politics"; System.out.println(s.name); System.out.println(s.sno); //System.out.println(s.subject); //s.eat(); s.study(); s.setSubject("JAVA big data"); System.out.println(s.getSubject()); } } /** * 2,We can encapsulate the attributes and functions of a class of things into a class component */ class Student { /** * 3,Premise: in order to improve the security of the program and call it in the way we specify * So we can encapsulate properties and methods in custom classes */ String name; int sno; /** * 4.1,Encapsulation attribute: encapsulate by private keyword * Resources decorated with private can only be used in this class */ private String subject; /** * 4.2,Add get and set methods of encapsulated attributes, that is, provide public attribute value acquisition / setting methods externally */ public String getSubject() { return subject; } public void setSubject(String subject) { this.subject = subject; } public void study() { System.out.println("Pretend to be learning C"); /** * 5.2: Access the functions of private methods in the public methods of this class */ eat(); } /** * 5.1: Method encapsulation: modify the access permission of the method to private */ private void eat() { System.out.println("I'm cooking"); } }
Description: how to access private
We can use the private keyword to encapsulate member variables and methods
About member variable method access:
- setXxx – public setting method provided externally
- getXxx - provides a public method of obtaining values externally
About member methods:
Put the private method in the public method for external calls
4 construction method
4.1 concept
Constructor is a special method. It is a method with the same name as the class and no return value type
The main function of constructor is to complete object creation or initialization
When a class creates an object (instantiation), the constructor is automatically called
Construction methods can also be overloaded like ordinary methods
4.2 form
It has the same name as the class and has no return value type. It can contain parameters or no parameters
4.2.1 construction method cases
public class TestConstructor { public static void main(String[] args) { /** * 1,A class will have a parameterless construction by default, and the construction method will be called automatically every time the object is instantiated */ Person p = new Person(); Person p2 = new Person("Monkey King"); Person p3 = new Person("Monkey King",800,"Wuxing mountain B1"); System.out.println(p.name); p.eat(); System.out.println(p3.name); System.out.println(p3.age); System.out.println(p3.address); } } class Person { String name;//full name int age;//Age String address;//address /** * 2,Constructor format: cut a method with the same name as the class and no return value type * Method format: modifier return value type method name (parameter list) {method body} */ public Person() { System.out.println("I am a nonparametric structure"); } /** * 3,Method overloading: there are multiple methods in the same class with the same method name but different parameter lists * 4,Constructors are overloaded */ public Person(String name) { System.out.println("I'm a parametric structure" + name); } public Person(String name, int age, String address) { // Formal parameter System.out.println("I'm a full parameter constructor"); this.name = name; this.age = age; this.address = address; } public void eat() { System.out.println("It's time for dinner~It's time for dinner~"); } }
How to remember constructors?
- Features: the method name is the same as the class name, and there is no return value type
- Execution timing: execute immediately when an object is created
- By default, a parameterless structure will be created. However, if a parameterless structure is customized, the default parameterless structure will be overwritten. Please add it manually
4.3 construction code block and local code block
4.3.1 form
{method body...}
4.3.2 characteristics of constructing code blocks
- Location: inside the class, outside the method
- Function: used to extract common codes in construction methods
- Execution timing: the construction code block will be called before each call of the construction method
- Note: construction code blocks take precedence over construction method loading
4.3.3 local code block
- Location: code block inside method
- Action: it is usually used to control the action range of variables. It will become invalid when there are curly braces
- Note: the smaller the scope of the variable, the better. There will be thread safety problems with member variables
4.3.4 loading sequence of test code blocks
//Execution sequence: // Construction code block - > construction method - > object creation success - > local code block /** * Summary: * 1,When creating an object, the program will automatically call the construction method, but if there is a construction code block, the construction code block will be executed first * Extract the common functions of all constructs and create objects after executing the construction method * 2,After the object is created, the method can be called through the object. If there is a local code block in the method, the corresponding local code block will be executed */ public class TestBlock { public static void main(String[] args) { /** * Each time an object is instantiated, a construction code block is executed */ Teacher t = new Teacher(); Teacher t1 = new Teacher(); Teacher t2 = new Teacher("Politics"); t.teach(); } } class Teacher { String subject; //Building building blocks /** * Construction code block: * Location: inside class, outside method * Execution timing: the constructor is triggered every time it is called, and the execution takes precedence over the constructor * Function: used to extract the common functions of all construction methods */ { subject = "JAVA Peiyou"; System.out.println("I'm building blocks"); } public Teacher() { System.out.println("Nonparametric structure" + subject); } /** * If multiple construction methods are constructed, the common content is extracted from the code block * However, individual construction methods need to define their own parameters. This parameter name can be used at this time * Set as the parameter of the method, the value passed when calling the method is what value */ public Teacher(String subject) { System.out.println("Parametric structure" + subject); } public void teach() { System.out.println("Teaching ing...."); /** * Local code block: * Location: in method * Execution timing: triggered only when the method of this code block is called * Action: control the action range of the variable. The smaller the action range of the variable, the better */ { int i = 10; System.out.println("Local code block"); System.out.println(i); } //System.out.println(i); An error will be reported because local variables can only be used locally } }
5 this keyword
5.1 concept
This represents a reference object of this class
5.2 form
5.3 use the variable names of this exercise at the same time
public class TestThis1 { public static void main(String[] args) { Cat c = new Cat(); c.eat(); } } class Cat { int sum = 20; int s = 30; public void eat() { int sum = 10; System.out.println(sum);// Proximity principle of variables System.out.println(s); /** * When a member variable has the same name as a local variable, we can use the this keyword to specify the member variable * Because the member variable belongs to class resources, the member variable will be released only when the class disappears * this Represents this class, which can be understood as Cat this = new Cat(); */ System.out.println(this.sum); } }
5.3.1 call between construction methods of this exercise
public class TestThis2 { public static void main(String[] args) { Dog d = new Dog(999); //d.Dog();// An error will be reported: you cannot actively call the constructor externally } } /** * this You can call the construction method * Note: it is unidirectional and cannot be called back and forth, which will cause an endless loop * this();--Call the parameterless construction of this class * this(Parameters)-- Call the parameter structure of the corresponding parameter of this class * this Related statements must be written on the first line */ class Dog { public Dog() { /** The function of the code: calling the parameter structure of this class in the structure without reference. */ //this(6666); System.out.println("Nonparametric structure"); } public Dog(int n) { this(); System.out.println("Parametric structure" + n); } }
5.4 OOP comprehensive exercises
public class TestOOP { public static void main(String[] args) { Teacher t1 = new Teacher(); Teacher t2 = new Teacher(666); Teacher t3 = new Teacher("Xiaxia",18,1000000.00,"Purple green sword"); } } class Teacher { private String name; private int age; private double salary; private String subject; public Teacher() { this(666); System.out.println("I am Teacher Nonparametric construction of class"); } public Teacher(int n) { System.out.println("I am Teacher Parametric construction of class" + n); // { // Local code block: in a method, used to control the range of variables // } } public Teacher(String name, int age, double salary, String subject) { System.out.println("I am Teacher All parameter construction of class"); this.name = name; this.age = age; this.salary = salary; this.subject = subject; } public void ready() { System.out.println("Preparing lessons ing....."); } public void teach() { System.out.println("Teaching ing....."); } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public double getSalary() { return salary; } public void setSalary(double salary) { this.salary = salary; } public String getSubject() { return subject; } public void setSubject(String subject) { this.subject = subject; } }
5.5 create object process
Person p = new Person();// A lot has happened in this short line of code
- Load the Person.class file into memory
- In the stack memory, open up space to store the reference variable p
- In the heap memory, open up space to store the Person object
- Default initialization of member variables
- Display initialization of member variables
- Execute the construction method (if there is a construction code block, execute the construction code block first and then the construction method)
- Heap memory complete
- Assign the address value of heap memory to variable p, which is a reference variable and refers to the address value of Person object