Classes and Objects
1. Three main lines of object-oriented learning:
* 1.Java Classes and their members: attributes, methods, constructors; Code Block, Internal Class * * 2.Big object-oriented features: encapsulation, inheritance, polymorphism,(Abstract) * * 3.Other keywords: this,super,static,final,abstract,interface,package,import etc. * * "Look big, start small"
2. Object-Oriented and Process-Oriented (Understanding)
- 1. Process Oriented: Emphasizes functional behavior and considers how to do it in the smallest unit of function.
- 2. Object Oriented: Emphasize functional objects, with classes/objects as the smallest unit, considering who does it.
Example comparison: People put elephants in the refrigerator.
3. Ideas for completing a project (or function):
4. Two important concepts in object-oriented:
Class: An abstract, conceptual definition of a class of things.
Object: is each individual of this kind of thing that actually exists and is therefore called an instance.
The focus of object-oriented programming is on class design
A design class is a member of a design class.
The relationship between them:
Object, derived from class new.
5. Rules for the implementation of object-oriented ideas
* 1.Create classes, design class members * 2.Create object of class * 3.By Object.Property or Object.Method calls the structure of the object
Supplement: Instructions for the use of several concepts
* attribute = Member variables = field = Domain, Field * Method = Member Method = function = method * Create object of class = Class Instantiation = instantiate
6. Creation of Objects and Memory Resolution of Objects
Typical code:
Person p1 = new Person();
Person p2 = new Person();
Person p3 = p1; // No new object was created, sharing an object entity in a heap space.
Explain:
If multiple objects of a class are created, each object has its own set of properties. (not static)
Meaning: if we modify the property a of one object, it will not affect the value of another object property a.
Memory Resolution:
7. Anonymous object: The object we created was not explicitly assigned a variable name. Anonymous object
Feature: Anonymous objects can only be called once.
Give an example:
new Phone().sendEmail(); new Phone().playGame(); new Phone().price = 1999; new Phone().showPrice();//0.0
Scenarios:
PhoneMall mall = new PhoneMall();
//Use of anonymous objects
mall.show(new Phone());
Where,
class PhoneMall{ public void show(Phone phone){ phone.sendEmail(); phone.playGame(); } }
8. Understand "Everything is an object"
1. In the Java language category, we all encapsulate functions, structures, etc. into classes, and call specific functional structures by instantiating classes
Scanner,String, etc.
Network resource: URL
2. When it comes to the interaction of Java language with front-end Html and back-end database, the front-end and back-end structures are reflected as classes and objects when interacting at the Java level.
9.JVM structure
After compiling the source program, one or more byte code files are generated.
We use the loader and interpreter of classes in the JVM to interpret and run the generated byte code file. This means that the class corresponding to the byte code file needs to be loaded into memory, involving memory resolution.
JVM Specification
The virtual machine stack is the stack structure mentioned in the ordinary time. We store local variables in the stack structure
Heap, we load the new out structure (such as arrays, objects) into paired spaces. Supplement: Object properties (not static) are loaded in heap space.
Method area: load information for classes, constant pools, static fields
2. One of the structures of a class: attributes
One of the two important structures in class design is attributes
Contrast: Attribute vs Local Variable
1. Identity:
* 1.1 Define the format of variables: data type variable names = Variable Value * 1.2 Declare before use * 1.3 Variables all have their corresponding scopes
2. Differences:
* 2.1 Different positions declared in a class * Attributes: A pair directly defined in a class{}within * Local variables: variables declared within methods, method parameters, code blocks, constructor parameters, and constructors * * 2.2 About the differences in permission modifiers * Attribute: When declaring an attribute, you can specify its permissions, using the permission modifier. * Common permission modifiers: private,public,By default, protected --->Encapsulation * Currently, when you declare attributes, you can just use the default. * Local variable: Permission modifiers cannot be used. * * 2.3 The default initialization value: * Attribute: The property of a class, according to its type, is initialized by default. * Integer ( byte,short,int,long: 0) * Floating point type ( float,double: 0.0) * Character type ( char: 0 (or'\u0000')) * Boolean type ( boolean: false) * * Reference data types (classes, arrays, interfaces: null) * * Local variable: There is no default initialization value. * This means that we must explicitly assign a value before calling a local variable. * Specifically: when a parameter is called, we assign a value. * * 2.4 Location to load in memory: * Attribute: Load into heap space (not static) * Local variable: loaded into stack space
Supplement: Review the classification of variables:
Mode 1: According to data type:
Mode 2: According to the position declared in the class:
3. Structure of Classes 2: Method
Two important structures in class design are methods
1. Method: Describe what the class should do.
* For example: Math Class: sqrt()\random() \... * Scanner Class: nextXxx() ... * Arrays Class: sort() \ binarySearch() \ toString() \ equals() \ ... * * 1.Give an example: * public void eat(){} * public void sleep(int hour){} * public String getName(){} * public String getNation(String nation){} * * 2. Method declaration: permission modifier returns value type method name(parameter list){ * Method Body * } * Be careful: static,final,abstract To decorate the method, let's talk later. * * 3. Explain: * 3.1 About permission modifiers: The permission modifiers for the default method are all used first public * Java Four permission modifiers are specified: private,public,By default, protected -->More on Packagability * * 3.2 Return value type: Return value vs No return value * 3.2.1 If a method returns a value, the type of return value must be specified when the method is declared. At the same time, you need to use * return Keyword to return a variable or constant of the specified type: return Data". * If the method does not return a value, use the void To represent. Typically, methods that do not return a value do not require * Use return.However, if used, only " return;"Indicates what it means to end this method. * * 3.2.2 Should we define a method that should not return a value? * ① Title Requirements * ② Experience: specific analysis of specific issues * * 3.3 Method name: belongs to the identifier, follows the rules and specifications of the identifier, "see name and know what" * * 3.4 Parameter list: Method can declare 0, 1, or more parameters. * 3.4.1 Format: Data Type 1 Parameter 1,Data Type 2 Parameter 2,... * * 3.4.2 Should we define parameters when we define methods? * ① Title Requirements * ② Experience: specific analysis of specific issues * * 3.5 Method body: The reflection of method function. * * 4. When using a method, you can call the properties or methods of the current class * * Special: Method A Method is called again in A:Recursive method. * In a method, you cannot define a method.
2.return keyword
1. Scope of use: Use in method body
2. Role:
(1) End method
(2) For methods of return value type, use the "return data" method to return the desired data.
3. Note: Execution statements cannot be declared after the return keyword.
3. Method overload
1. The concept of method overload
Definition: More than one method with the same name is allowed in the same class as long as they have different number or type of parameters.
Summary: "Two identical are different":
Same class, same method name
Different parameter lists: different number of parameters, different parameter types
2. Examples of overloads:
Example 1: overloaded sort() / binarySearch() in the Arrays class; println() in PrintStream
Example 2:
//The following four methods make up the overload public void getSum(int i,int j){ System.out.println("1"); } public void getSum(double d1,double d2){ System.out.println("2"); } public void getSum(String s ,int i){ System.out.println("3"); } public void getSum(int i,String s){ System.out.println("4"); }
Examples that do not constitute an overload:
//The following three methods do not overload the four above methods // public int getSum(int i,int j){ // return 0; // } // public void getSum(int m,int n){ // // } // private void getSum(int i,int j){ // // }
3. How can I determine if it constitutes a method overload?
Judged strictly by definition: two identical are different.
It doesn't matter with the permission modifier, return value type, parameter variable name, method body of the method!
4. How to determine the call to a method in a class:
Method Name--->Parameter List
Interview Question: The difference between overloading and rewriting methods?
throws\throw
String\StringBuffer\StringBuilder
Collection\Collections
final\finally\finalize
...
Abstract classes, interfaces
sleep() / wait()
3. Method of Variable Number of Parameters
1. Instructions for use:
* 1.jdk 5.0 What's New * 2.Specific use: * 2.1 Format of variable number parameters: data type ... Variable Name * 2.2 When calling a method with variable number of parameters, the number of parameters passed in can be: 0, 1,2 One,.... * 2.3 Methods with variable number of parameters have the same method name as those in this class, and overloads occur between methods with different parameters * 2.4 Methods with variable number of parameters have the same method names as in this class, and arrays with the same parameter types do not constitute overloads. In other words, they cannot coexist. * 2.5 Variable number of parameters In method parameters, must be declared at the end * 2.6 Variable number of parameters in method parameters,At most one deformable parameter can be declared.
2. Examples:
public void show(int i){ } public void show(String s){ System.out.println("show(String)"); } public void show(String ... strs){ System.out.println("show(String ... strs)"); for(int i = 0;i < strs.length;i++){ System.out.println(strs[i]); } } //Cannot coexist with the previous method // public void show(String[] strs){ // // }
On call:
test.show("hello"); test.show("hello","world"); test.show(); test.show(new String[]{"AA","BB","CC"});
4. Value Passing Mechanism in Java
1. Examples of assignments to variables within a method:
System.out.println("***********Basic data types:****************"); int m = 10; int n = m; System.out.println("m = " + m + ", n = " + n); n = 20; System.out.println("m = " + m + ", n = " + n); System.out.println("***********Reference data type:****************"); Order o1 = new Order(); o1.orderId = 1001; Order o2 = o1;//After assignment, the address values of o1 and o2 are the same, pointing to the same object entity in heap space. System.out.println("o1.orderId = " + o1.orderId + ",o2.orderId = " +o2.orderId); o2.orderId = 1002; System.out.println("o1.orderId = " + o1.orderId + ",o2.orderId = " +o2.orderId);
Rules:
If the variable is a basic data type, the value assigned is the data value that the variable holds.
If the variable is a reference data type, then the value assigned is the address value of the data the variable holds.
2. Parameter concepts for methods
Parameters: Parameters in parentheses declared when a method is defined
Arguments: The data actually passed to the parameter when the method is called
3. Parameter Passing Mechanism in java: Value Passing
Rules:
- If the parameter is a basic data type, then the argument is assigned to the parameter the data value it actually stores.
- If the parameter is a reference data type, then the argument is assigned to the parameter the address value where the parameter stores the data.
Extension:
If the variable is a basic data type, the value assigned is the data value that the variable holds.
If the variable is a reference data type, then the value assigned is the address value of the data the variable holds.
4. Typical examples and memory parsing:
[Example 1]
[Example 2]
5. Recursive methods
1. Definition: Recursive method: A method calls itself within its body.
2. How do you understand recursion?
Method recursion contains an implicit loop that repeats a piece of code without loop control.
Recursion must recurse in a known direction, otherwise it becomes infinite, similar to a dead cycle.
3. Examples:
// Example 1: Calculate the sum of natural numbers between 1-n public int getSum(int n) {// 3 if (n == 1) { return 1; } else { return n + getSum(n - 1); } } // Example 2: Calculate the product of natural numbers between 1-n: n! public int getSum1(int n) { if (n == 1) { return 1; } else { return n * getSum1(n - 1); } } //Example 3: A known sequence is f(0) = 1,f(1) = 4,f(n+2)=2*f(n+1) + f(n), //Where n is an integer greater than 0, find the value of f(10). public int f(int n){ if(n == 0){ return 1; }else if(n == 1){ return 4; }else{ // return f(n + 2) - 2 * f(n + 1); return 2*f(n - 1) + f(n - 2); } } //Example 4: Fibonacci series //Example 5: Hannotta problem //Example 6: Quick Row
4. Object-Oriented Features 1: Encapsulation
Object-oriented feature one: encapsulation and hiding
1. Why should encapsulation be introduced?
Our programming pursues "high cohesion, low coupling".
High cohesion: the internal data manipulation details of a class are self-contained and external interference is not allowed;
Low coupling: Only a small number of methods are exposed for use.
Hide the complexity inside the object and only expose simple interfaces to the outside world. Easy to call from outside, so as to improve the scalability and maintainability of the system. As the saying goes, hide the hidden and expose the exposed. This is the design idea of encapsulation.
2. Problem introduction:
When we create an object of a class, we can assign the attributes of the object in the way of Object.Attribute. Here, the assignment operation is constrained by the data type and storage range of the attribute. There are no other restrictions. However, in practice, we often need to add additional restrictions to attribute assignment. This condition cannot be reflected in the property declaration, we can only add restrictions through the method. (For example, setLegs() and we need to avoid users from assigning attributes in the way of Object.Attribute. You need to declare the property private.
-->At this point, encapsulation is reflected for attributes.
3. Encapsulation ideas specific code manifestations:
Implications 1: Privateize the class property xxx while providing a public method to get (getXxx) and set (setXxx) the value of this property
private double radius;
public void setRadius(double radius){
this.radius = radius;
}
public double getRadius(){
return radius;
}
Reflections 2: Private methods of not exposing to the outside world
Reflect three: the singleton pattern (privatizing the constructor)
Reflection 4: If you do not want the class to be called outside the package, you can set the class as the default.
4. Four permission modifiers specified in Java
4.1 The order of permissions from smallest to largest is: private < default < protected < public
4.2 Specific range of modifications:
4.3 Permission modifiers can be used to modify the structure of the description:
Four permissions can be used to modify the internal structure of a class: attributes, methods, constructors, internal classes
Modifier class, can only be used: default, public
5. Structure of Classes 3: Constructors
1. Constructor (or construction method): Constructor
The role of the constructor:
* 1.create object * 2.Information for initializing objects ## 2. Instructions for use: * 1.If there is no constructor that explicitly defines the class, a constructor with an empty parameter is provided by default * 2.Define the format of the constructor: permission modifier class name(parameter list){} * 3.Multiple constructors defined in a class that overload each other * 4.Once we explicitly define the constructor for the class, the default empty parameter constructor is no longer available * 5.There will be at least one constructor in a class.
3. Examples:
//constructor public Person(){ System.out.println("Person()....."); } public Person(String n){ name = n; } public Person(String n,int a){ name = n; age = a; }
4. Attribute assignment order
* Summary: Order of attribute assignments * * * ① Default Initialization * ② Explicit Initialization * ③ Initialization in Constructor * ********************** * ④ adopt"object.Method" or "object.attribute"Method, assignment * * The order of operations above:① - ② - ③ - ④
5.JavaBean
A JavaBean is a Java class that meets the following criteria:
Classes are public
A public constructor with no parameters
Property, and corresponding get, set methods
6. Keyword: this
1. Callable structures: properties, methods; constructor
2.this calls properties and methods:
this is understood as: the current object or the object currently being created
* 2.1 In the class method, we can use"this.attribute"or"this.Method"To call the current object property or method. However, * Normally, we choose to omit"this.". In special cases, if the formal parameters of the method and the properties of the class have the same name, we must explicitly * Use"this.variable"This means that the variable is an attribute, not a formal parameter. * * 2.2 In the constructor of a class, we can use"this.attribute"or"this.Method"To call the object property or method currently being created. Often, however, we choose to omit"this.". In special cases, we must explicitly * Use"this.variable"This means that the variable is an attribute, not a formal parameter.
3.this calls the constructor:
(1) In the constructor of a class, we can explicitly use the "this (parameter list)" method to invoke other constructors specified in this class
(2) You cannot call yourself by "this (parameter list)" in the constructor
(3) If there are n constructors in a class, at most n-1 constructors use "this (parameter list)"
(4) Provides that "this (list of formal parameters)" must be declared in the first line of the current constructor
Inside a constructor, at most one "this (parameter list)" can be declared to invoke other constructors
7. Keyword: package, import
1. Use of packages
1.1 Instructions for use:
- 1. Provide package concepts for better class management in your project
- 2. Use the package to declare the package to which the class or interface belongs, declaring at the beginning of the source file
- 3. Package, which is an identifier, follows the naming rules for identifiers, specifications (xxxyyzzz), and "Know your name"
- 4. Every'.. Once, it represents a layer of file directory.
1.2 Examples:
Example 1:
A shipping software system consists of a set of domain objects, GUI and reports subsystems
Example 2: MVC design pattern
The main introduction in 1.3 JDK:
2. Use of import:
import:Import
* 1. Explicit use in source files import Structure imports classes, interfaces under specified packages * 2. Declarations are between package and class declarations * 3. If multiple structures need to be imported, write them side by side * 4. have access to"xxx.*"Means that you can import xxx Structure under Package * 5. If the class or interface used is java.lang If defined under a package, it may be omitted import structure * 6. If the class or interface used is defined under this package, it may be omitted import structure * 7. If a class with the same name under different packages is used in the source file, at least one class must be displayed as the full class name. * 8. Use"xxx.*"Method indicates that it can be invoked xxx The structure under the package. But if you are using xxx Structures under subpackages still need to be explicitly imported * 9. import static:Import static structure in specified class or interface:Property or method.