Java – object oriented (OO)
Object oriented and process oriented
A classic question,
Put the elephant in the refrigerator in several steps.
For process oriented thinking.
Three steps,
Open the refrigerator
Put it in
Close the refrigerator
But for the object-oriented idea
Two objects are involved in the problem
Elephant refrigerator is always the object of the problem
So the behavior of the refrigerator is
Refrigerator - > open the door
Refrigerator - > loading
Refrigerator - > door closing
Then the behavior of the object is determined. We organize the behavior of the object and complete the whole problem.
It is not difficult to see that the object-oriented thought includes the process oriented thought. Only object-oriented stands at a higher level to look at the solution to the problem.
Concepts and differences of OOA, ood and OOP
OOA (object oriented analysis, object oriented analysis method)
OOA is to analyze the problem according to the object-oriented idea after the system business investigation in the development process of a system. OOA is quite different from structured analysis. OOA emphasizes the classification, analysis and sorting of the materials required for OO methods on the basis of systematic investigation data, rather than the analysis of the current situation and methods of management business.
OOA (object-oriented analysis) model consists of five levels (topic layer, object class layer, structure layer, attribute layer and service layer) and five activities (identifying object class, identifying structure, defining topic, defining attribute and defining service). In this method, the structure between two object classes is defined, one is called classification structure, and the other is called assembly structure. Classification structure is the so-called relationship between general and special. The assembly structure reflects the relationship between the whole and part of the object.
OOA should identify instance connections while defining attributes. Instance connection is the mapping relationship between one instance and another.
OOA should identify message connections while defining services. When an object needs to send a message to another object, there is a message connection between them.
The five levels and five activities in OOA continue to run through the OOD process. The OOD model consists of four parts. They are design problem domain part, design human-computer interaction part, design task management part and design data management part.
OOD (object oriented design)
OOD method is an intermediate transition link in OO method. Its main function is to further standardize the results of OOA analysis, so that they can be directly accepted by OOP.
Object oriented design (OOD) is a software design method and an engineering specification. There is no doubt about it. According to Bjarne Stroustrup, the paradigm of object-oriented programming is:
1. Decide the class you want;
2. Provide a complete set of operations for each class;
3. Explicitly use inheritance to show common ground.
From this definition, we can see that OOD is "the process of determining the required classes, class operations and associations between classes according to requirements".
The goal of OOD is to manage the interdependence of various parts within the program. In order to achieve this goal, OOD requires that the program be divided into blocks. The scale of each block should be small enough to be managed, and then each block should be hidden behind the interface to communicate with each other only through the interface. For example, if you use the OOD method to design a server client application, there should be no direct dependence between the server and the client, but the server interface and the client interface should be interdependent.
The transformation of this dependency makes each part of the system reusable. In the above example, the client does not have to rely on a specific server, so it can be reused in other environments. If you want to reuse a program block, just implement the necessary interface.
Ood is a design paradigm to solve software problems, an abstract paradigm. Using the design paradigm of OOD, we can use objects to represent the entities of the problem domain, and each object has a corresponding state and behavior. We just said: ood is an abstract paradigm. Abstraction can be divided into many levels, from very general to very special, and objects can be at any level of abstraction. In addition, objects that are different from each other but related to each other can form an abstraction: as long as they are similar, they can be treated as objects of the same class.
OOP (Object Oriented Programming)
OOP is a computer programming architecture. A basic principle of OOP is that a computer program is composed of a single unit or object that can play the role of a subroutine. OOP achieves three main goals of software engineering: reusability, flexibility and scalability. In order to realize the overall operation, each object can receive information, process data and send information to other objects. OOP mainly includes the following concepts and components:
Component - a unit formed by data and functions together in a running computer program. Components are the basis of modules and structures in OOP computer programs.
Abstraction - the ability of a program to ignore certain aspects of the information being processed, that is, the ability to focus on the main aspects of the information.
Encapsulation - also known as information encapsulation: ensure that components do not change the internal state of other components in unexpected ways; Only those components that provide internal state change methods can access their internal state. Each type of component provides an interface to contact other components and specifies the methods called by other components.
Polymorphism - component references and class assemblies involve many other different types of components, and the results of referencing components depend on the type of actual call.
Inheritance - allows the creation of subclass components based on existing components, which unifies and enhances polymorphism and encapsulation. Typically, a class is used to group components, and a new class can be defined as an extension of an existing class. In this way, classes can be organized into a tree or network structure, which reflects the universality of actions.
Because of abstraction, encapsulation, reusability and ease of use, component-based programming has become particularly popular in scripting languages. Python and Ruby are recently emerging languages, which fully adopt the idea of OOP during development, and the popular Perl scripting language has slowly added new object-oriented functional components since version 5. Using components to replace "real" entities has become the reason why JavaScript (ECMAScript) is popular. It has been demonstrated that the appropriate combination of components can replace the document object model (DOM) of HTML and XML on the Internet.
The result of OOA can be used as the model of OOD, and the result of OOD can be used as the blueprint of OOP. OOP implements a system according to the blueprint provided by ood.
Three characteristics of object oriented
- encapsulation
- inherit
- polymorphic
Objects and classes
Object, what we call object, is a concrete thing in reality.
In code, an object is a piece of "memory" in the specific running process of a program.
Class is an abstract description of a class of things in reality. Class is a concept.
Class mainly has two points: one is the common characteristics (state) of things, and the other is the common behavior of things. (state and behavior, properties and methods)
In Java, a class is a piece of code, and it is also a data type.
A class is an abstract description of an object. An object is a concretization and instantiation of a class.
Construction method
In each class, there will be a method with the same name (which can be written, not written, or overridden). Its function is to create class objects.
- Class constructor cannot have a return value
- The construction method of the class must be consistent with the class name
- If no constructor is defined, the compiler will automatically define a parameterless constructor. If a constructor is defined, the compiler will not create it.
- Construction methods can be overloaded
Of course, if there is method overloading, there should be the case that the names of variables or attributes are consistent - In the construction method, this represents the attribute of the currently created variable.
- In common methods, it represents the current call method attribute.
Instantiation:
package com.sdut.demo; public class Student { public static void main(String[] args) { Student student = new Student(); //Class - > object --- instantiation } }
encapsulation
-
Generalized encapsulation
The process of writing a class is an encapsulation process
Packaging should follow high cohesion and low coupling
High cohesion: functions are highly centralized. A class should not have too many functions.
Low coupling: the fewer connections between functions, the better -
Narrow packaging
In Java, the internal information in the class should be hidden as much as possible.
That is, all the attributes in the class are decorated with private to make them private attribute variables
By constructing public attribute methods, namely get and set methods
Constructor - Method with the same name as the class name - method overloading
Methods of directly manipulating attributes
The process of encapsulation is the process of data encapsulation, that is, the encapsulation of attributes and the protection of data. That is, privatized attribute variables and public attribute methods
The first letter of the attribute must be lowercase. Except for id, the length of the attribute variable must not be less than three characters.
package com.sdut.demo; public class Student {//Entity class private String name; private int age; private String sex; 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 String getSex() { return sex; } public void setSex(String sex) { this.sex = sex; } }
Get and set the value of the property through the get and set methods, which can prevent other classes from directly operating the property variable of the current class, that is, to protect data
Meaning of encapsulation: (code reuse)
- Hide implementation details in classes
- Operation data can only be accessed through defined methods to facilitate control and limit unreasonable operations on attributes
- It is convenient for maintenance and modification and increases the maintainability of the code
A simple little exercise:
//Entity class package com.sdut.demo01; public class StudentModel { private int id; private String name; private String sex; private int age; private String major; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getSex() { return sex; } public void setSex(String sex) { if (sex.equals("male") || sex.equals("female")) { this.sex = sex; } } public int getAge() { return age; } public void setAge(int age) { if(age > 0) { this.age = age; } } public String getMajor() { return major; } public void setMajor(String major) { this.major = major; } }
//Implementation class package com.sdut.demo01; import java.util.ArrayList; import java.util.Scanner; import org.junit.Test; public class Function { Scanner sc = new Scanner(System.in); ArrayList<StudentModel> arrl = new ArrayList<>(); public void allFunction() { while(true) { System.out.println("------system options------"); System.out.println("-----01 Input information-----"); System.out.println("----02 Query all information---"); System.out.println("----03 Query by name---"); System.out.println("-----04 Add specialty-----"); System.out.println("---05 Query by specialty---"); System.out.println("-----input e Exit this operation-----"); String in = sc.nextLine(); if (in.equals("e")) { return; } switch (in) { case "01": inputs(); break; case "02": checkAll(); break; case "03": nameCheck(); break; case "04": addMajor(); break; case "05": majorCheck(); break; default: break; } } } @Test public void inputs() { while (true) { input(); System.out.println("Continue to enter:(y/n)"); if (sc.nextLine().equals("n")) { break; } } } @Test public void input() { StudentModel stu = new StudentModel(); System.out.println("Enter the student number, for example: 001"); stu.setId(Integer.parseInt(sc.nextLine())); System.out.println("Enter a name,"); stu.setName(sc.nextLine()); System.out.println("Enter gender,"); stu.setSex(sc.nextLine()); System.out.println("Enter age,"); stu.setAge(Integer.parseInt(sc.nextLine())); arrl.add(stu); } public void checkAll() { for (StudentModel s : arrl) { System.out.println("Student number" + s.getId()); System.out.println("full name" + s.getName()); System.out.println("Gender" + s.getSex()); System.out.println("Age" + s.getAge()); System.out.println("major" + s.getMajor()); } } public void majorCheck() { System.out.println("Enter the specialty to query"); String m = sc.nextLine(); for (StudentModel s : arrl) { if (s.getMajor().equals(m)) { System.out.println("Student number" + s.getId()); System.out.println("full name" + s.getName()); System.out.println("Gender" + s.getSex()); System.out.println("Age" + s.getAge()); } } } public void nameCheck() { System.out.println("Enter the name to query"); String m = sc.nextLine(); for (StudentModel s : arrl) { if (s.getName().equals(m)) { System.out.println("Student number" + s.getId()); System.out.println("Gender" + s.getSex()); System.out.println("Age" + s.getAge()); System.out.println("major" + s.getMajor()); } } } public void addMajor() { for (StudentModel s : arrl) { if(s.getMajor() != null) { continue; } System.out.println("full name" + s.getName()); System.out.println("Please enter major:"); s.setMajor(sc.nextLine()); } } }
//control class package com.sdut.demo01; import java.util.Scanner; public class Control { static Scanner sc = new Scanner(System.in); public static void main(String[] args) { Function fuc = new Function(); while (true) { fuc.allFunction(); System.out.println("input e End system"); if ("e".equals(sc.nextLine())) { return; } } } }
inherit
The subclass inherits the characteristics and behavior of the parent class, so that the object of the subclass has the characteristics and behavior of the parent object, so that the subclass has the instance domain and method of the parent class, or the method inherited by the subclass from the parent class, so that the subclass has the same behavior as the parent class.
Inheritance is a cornerstone of Java object-oriented programming because it allows the creation of hierarchical objects.
Inheritance needs to conform to the relationship: is-a, the parent class is more general, and the child class is more specific.
In this relationship of inheritance,
- The class inherits all the properties and methods of the parent class (non private properties and methods).
- Classes can also extend their properties and methods.
- Subclasses can override the methods of the parent class, that is, implement the methods of the parent class in their own way.
- A subclass can define attributes consistent with the parent class, but not the same.
- A class can only have one direct parent class (single inheritance).
- Inheritance is transitive (that is, a character class can inherit the properties and methods inherited by its parent class)
- The constructor will not be inherited (constructive) (the constructor is not a method, so it will not be inherited). Although it will not be inherited, the constructor of the parent class will be called first, and then the constructor of the child class will be called when the word class creates an object.
- Improved coupling between classes.
Subclasses contain things that can be accessed using the parent class.
Parent class: base class, superclass, parent class
Subclasses: derived classes
Simple inheritance:
package com.sdut.demo05; public class Demo01 { public int a = 0; public String b = "aaa"; public static void test01(){ System.out.println("inherit"); } }
package com.sdut.demo05; public class Demo02 extends Demo01{ public static void main(String[] args) { test01(); } }
Java supports single inheritance, not multiple inheritance, but multiple inheritance. (a son can only have one father, but one father has multiple sons)
Object
Object is the superclass (base class) of all classes by default
When a class has no parent class, it directly inherits Object by default.
[the external chain image transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-bpemhc3b-1627861982036) (C: \ users \ j-adan \ appdata \ roaming \ typora user images \ image-20210726201141813. PNG)]
[the external chain image transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-vsgxvieih-1627861982043) (C: \ users \ j-adan \ appdata \ roaming \ typora user images \ image-20210726201335438. PNG)]
You can inherit the methods and properties of the direct parent class or the properties and methods of the indirect parent class.
The difference between Overload and Override
answer:
- Overload and Override are both expressions of Java polymorphism.
- Overload means overload. It is a manifestation of polymorphism in a class, that is, the names of methods are the same, but the parameter lists are different, or the order of parameter lists is different.
- Override means override. It is a form of polymorphism between parent and child classes, that is, the method name is the same, the parameter list is the same, and the return type is the same. However, when the child object uses this method, the method overridden by the child class will be called.
”=="What's the difference between the and equals method?
answer:
- ” "Equals" is a comparison operator provided by Java. When comparing basic data types, although the data types are different, the values are equal, that is, it returns true. When comparing reference data types and two reference variables have the same type or parent-child relationship, it can compare to judge whether the addresses are the same. Equals is a method in the Object class, which actually returns It is the result of the "" judgment, but it compares the address, and pay special attention to the rewriting of equals
Example:
package com.sdut.demo; public class Demo01 { public static void main(String[] args) { // -Between 128 and + 127 Integer a = 5; int b = 5; Integer c = new Integer(5); Integer d = 5; System.out.println("-128 ~ +127 between"); System.out.println(a.equals(b)); System.out.println(a == b); System.out.println(a.equals(c)); System.out.println(a == c); System.out.println(a == d); // -Beyond 128 ~ + 127 a = 128; b = 128; c = new Integer(128); d = 128; System.out.println("-128 ~ +127 outside"); System.out.println(a.equals(b)); System.out.println(a == b); System.out.println(a.equals(c)); System.out.println(a == c); System.out.println(a == d); } }
Output results:
-Between 128 and + 127
true
true
true
false
true
-Beyond 128 ~ + 127
true
true
true
false
false
Focus on the difference between "= =" and equals outside the Integer constant pool. The two results are different, because the Integer class will rewrite the equals method to judge not the address, but the value inside. Not only Integer, but also String will rewrite the equals method to judge that the value inside is the same
- [force] the values of all wrapper objects of the same type are compared using the equals method.
- Note: for Integer var =? For assignments in the range of - 128 to 127, the Integer object is
- IntegerCache. When the cache is generated, the existing objects will be reused. The Integer value in this interval can be directly calculated with = =
- Judgment, but all data outside this interval will be generated on the heap and will not reuse existing objects. This is a big pit,
- It is recommended to use the equals method for judgment.
hashCode
Hash value local method
polymorphic
Method override rule:
- The parameter list must be exactly the same as the overridden method
- The return type must be exactly the same as the overridden method
- The access permission cannot be lower than that of the overridden method in the parent class. For example, the access permission in the parent class is public, and protected cannot be used in subclasses
- A member method of a parent class can only be overridden by its child class.
- A method declared final cannot be overridden
- Methods declared as static cannot be overridden, but can be declared again
- If the subclass and the parent class are in the same package, the subclass can override all methods in the parent class, except private and final modified methods.
- A subclass and a parent class are not in the same package. A subclass can only override non final methods declared as public protected by the parent class.
- Constructor cannot be overridden
- If you cannot inherit a method, you cannot override it.
- The rewritten method can throw any non mandatory exception, regardless of whether the rewritten method throws an exception or not. However, the rewritten method cannot throw a new mandatory exception, or declare more extensive exceptions than the rewritten method, and vice versa.
Upward transformation
When the object is transformed upward, the calling rule is to call the member of the class where the variable type is located. However, if the method overridden is called, the method overridden in the subclass is called.
Automatic upward Transformation:
The subclass object is assigned to the parent object.
Forced downward Transformation:
Unlike forced type conversion, it can only be converted from superior to subordinate.
instanceof:
Determine whether an instance object is an instance of a class.