Object oriented OPP (I)
Classes and objects
Concept of class:
The description of a class of things is an abstract and conceptual definition. For example, human beings with abstract concepts are an abstract class. The class belongs to the reference data type, and the address value is assigned during assignment.
Concept of object:
Each individual of this kind of things actually exists is an object in java code. For example, every human being is an object and an instance. new objects are stored in heap space.
The key point of object-oriented programming is class design and class member design
Case:
-
People put elephants in the refrigerator [process oriented and object-oriented thinking]
Process oriented program: it emphasizes the functional behavior and considers how to do it with the function as the minimum unit
Open the refrigerator door Lift the elephant Close the refrigerator door
Object oriented program: emphasize the objects with functions, take the class / object as the minimum unit, and consider who will do what and who has what functions
#Antecedent class class people{ #Design method Open (refrigerator){ Refrigerator.Open the door(); } lift(elephant){ elephant.get into(Refrigerator); } close(Refrigerator){ Refrigerator.close(); } } class Refrigerator{ Open the door(){ } close(){ } } class elephant{ get into(Refrigerator){ } }
Compared with process oriented, object-oriented looks more cumbersome with fewer steps, but in actual development, object-oriented is more suitable. If you need to add any functions, you only need to add corresponding functions in the corresponding classes
Code level:
If a class creates multiple objects, each object has an independent set of properties (non static)
###Memory level:
At the memory level, we mainly pay attention to the reference data type, because the reference data type points to the address value
The stack space stores local variables, while the heap space stores object instances from new, and the String type is in the constant pool in the method area.
Class is created from an instantiated object
Design a class of "people", and people bring some properties and a method (behavior)
public class PersonTest{ public static void main(String[] args){ //Create object instantiation Person p1 = new Person(); //Object call method p1.eat(); p1.sleep(); } } class Person{ //attribute String name; int age; boolean isMale; //method public void eat(){ System.out.println("People can eat"); } public void sleep(){ System.out.println("People can sleep"); } }
Class (member variables have default values)
Class structure - properties
Concept:
Describing things in life is nothing more than describing the attributes and behaviors of things, such as people's height, weight and other attributes
Attribute = member variable = field = field / field
Attributes are divided into: = = member variables (attributes) = = and local variables
Classification:
Classification by data type
Classification by location in class
Differences about permission modifiers
Properties (member variables):
- When declaring a property, you can specify its permission and use the permission modifier
- Common permission modifiers: private, public, default and protected reflect encapsulation
Local variables:
- Permission modifiers are not allowed
The default initialization value of the property
type | Default initialization value |
---|---|
Integer (byte, short, int, long) | 0 |
Floating point type (float, double) | 0.0 |
Character type (char) | 0 or \ u0000 |
Boolean | false/0 |
Reference data type (class, interface, array) | null |
Local variable: no default initialization value
This means that we must explicitly assign values before calling local variables
Location loaded in memory:
Properties: load into heap space (non static)
Local variables: loading into stack space
Class structure - Method
Concept:
Describe the functions that a class should have (what to do, what behavior to have)
Method = function = method
The method name needs to be known as far as possible
Classification:
Methods are divided into methods with return value, methods without return value, methods with formal parameters and methods without formal parameters, which depends on whether there is a void keyword and formal parameter list and whether there are formal parameters
No return value | There is a return value | |
---|---|---|
Invisible parameter | void method name () {} | Return value type method name () {} |
Formal parameter | void method name (formal parameter list) {} | Return value type method name (formal parameter list) {} |
public void test1(){ System.out.println("This is an invisible parameter and has no return value"); } public void test1(String t1){ System.out.println("This is a method with formal parameters and no return value"); } public String test2(){ return "This is a method with return value and no formal parameters"; } public String test2(String t1){ return "This is a method with return value and formal parameters"; }
Whether there is a return value depends on void. If there is no void, there is a return value. You can use return to return and receive. If there is void, return can only terminate
Permission modifier:
Modifier name | Inside of class | Same package | Subclasses of different packages | Same project |
---|---|---|---|---|
private | ✔ | |||
Default (default) | ✔ | ✔ | ||
protected | ✔ | ✔ | ✔ | |
public | ✔ | ✔ | ✔ | ✔ |
Formal parameter
Formal parameters are optional, depending on the subject and whether user input is required. The number of formal parameters is unlimited, and different formal parameters are separated by commas
public void test1(){ System.out.println("This is a method that does not require formal parameters"); } public void test1(String t1,double t2,int t3){ System.out.println("You can have any number of formal parameters"+t1); }
return keyword
Usage: used inside the method body
**Note: * * if the method has a return value, it receives the return value. If the method has no return value, it ends the method
Use of methods:
In the method, you can also call other properties and methods of the current class
**Special: * * method A is called in method A, which is called recursive method call
Method overload:
More than one method with the same name is allowed in the same class, as long as their parameter number or parameter type are different. (the formal parameter names are the same, but the formal parameter lists are different)
public void overloadTest(){ System.out.println("Overload method 1"); } public void overloadTest(String t1){ System.out.println("Overload method 2"); } public void overloadTest(int i1){ System.out.println("Overload method 3"); }
These methods with the same name are called method overloads because they are known by name. For example, int arrays and double arrays need to be sorted. If it is troublesome to create two methods with different names, they have the same name and have the same functions, which is also convenient
Case:
Variable number parameter: belongs to jdk5 0 new content
Format: (data type... Variable name)
When calling a method with variable number of formal parameters, the number of parameters passed in can be 0, 1, 2... Multiple. The incoming formal parameters need to be of the same type
public class ChangeFormal { public static void main(String[] args) { RectangleTest rectangleTest1 = new RectangleTest(); rectangleTest1.overloadTest("ni","hao","a!"); } public void overloadTest(String ... i1){ System.out.println("Variable number parameter"); for (int i = 0; i < i1.length; i++) { System.out.println(i1[i]); } } }
Variable number formal parameters can only be declared in a method, and can only be declared at the end
//correct public void overloadTest(int i1,int i2,int i2,int ... i3){ } //FALSE //public void overloadTest(String ... s1,int i1){ //}
Arrays with the same method name and parameter type as those in this class do not constitute overloads = = In other words, the two cannot coexist. Arrays and deformable parameters cannot coexist (do not constitute overloading)==
//The two cannot coexist. They are essentially the same thing public void overloadTest(String[] s1){ } public void overloadTest(String ... s1){ }
Moreover, the traversal of variable type parameters is the same as that of array types
Value Passing Mechanism:
Rules:
- If the variable is a basic data type, the address value saved by the variable is assigned at this time
- If the variable is a reference data type, the assigned value is the address value of the data saved by the variable
Parameters in method:
Formal parameters:
The parameters in parentheses declared when the method is defined
Argument:
The data actually passed to the formal parameter when the method is called
Case and memory analysis:
Examples of basic data types
Reference data type example
Other examples
Because if you follow the wrong answer, the first setting except yourself is 1, and the subsequent ones are all except 1 of the guard position, you can either reverse it or assign it to another variable
Recursion:
Concept:
-
A method body calls itself
-
Method recursion contains an implicit loop that repeats a piece of code, but this repetition does not require loop control
-
Recursion must recurse in the known direction, otherwise this recursion will become infinite recursion, similar to dead loop
Case:
p216 example, the sum and product of natural numbers within 100 of recursive method
p217 recursive sequence, fiboracci sequence, Hanoi Tower problem, quick sort
Object Oriented Feature -- encapsulation
concept
When we use the washing machine, we only need to click, but we don't need to understand the internal composition of the washing machine. This is called encapsulation.
Encapsulation - high cohesion, low coupling
use:
The private keyword is mainly used to encapsulate the properties or methods in the class, but the corresponding getter and setter methods are usually reserved to read and store data.
//IDEA shortcut: alt+shift+s public class Circle { private int i1; private int i2; public int getI1() { return i1; } public void setI1(int i1) { this.i1 = i1; } public int getI2() { return i2; } public void setI2(int i2) { this.i2 = i2; } }
reflect:
-
We privatize the property of the class and provide public methods to get (getxxx) and set the value of this property
-
Create a method to be used in the class without external exposure
Permission modifier:
Note: for the permission modifier of class class, you can only use public and default (default).
Modifier name | Inside of class | Same package | Subclasses of different packages | Same project |
---|---|---|---|---|
private | ✔ | |||
Default (default) | ✔ | ✔ | ||
protected | ✔ | ✔ | ✔ | |
public | ✔ | ✔ | ✔ | ✔ |
These four permissions can be used to modify classes and their internal structures: properties, methods, constructors, and internal classes
Case:
public class Person { private int age; public int getAge() { return age; } public void setAge(int age) { this.age = age; } } //Test class public class PersonTest { public static void main(String[] args) { Person p1 = new Person(); p1.setAge(12); System.out.println("Age:"+p1.getAge()); } }
Class structure -- constructor (construction method)
Concept:
Initialize the properties of the object while creating the object
explain:
- If no class constructor is explicitly defined, the system will provide an empty parameter constructor by default
- **Format: * * permission modifier with the same name as class (formal parameter list) {}
- Multiple constructors defined in a class constitute overloads with each other
- Once we explicitly define the class constructor, the system no longer provides the default null parameter constructor
- There will be at least one constructor in a class
Difference between constructor and method:
On the Internet, constructors are understood as a special method. In fact, constructors are not equivalent to methods. Firstly, the form of constructors is different from methods. Secondly, the role of constructors is to create objects, and the role of methods is to encapsulate functions and then be called by objects. In addition, in the java api, constructors and methods are separated and parallel structures. It can be seen that the two are not the same
Case:
public class Person { private int age; private String name; public Person(){ age = 18; } public Person(String s1,int i1){ age = i1; name = s1; } public String getName() { return name; } public void setName(String name) { this.name = name; } }
public class TriAngle { private double base; private double height; public TriAngle() { } public TriAngle(double base, double height) { this.base = base; this.height = height; } public double getBase() { return base; } public void setBase(double base) { this.base = base; } public double getHeight() { return height; } public void setHeight(double height) { this.height = height; } public double findArea(){ return base*height*2; } } //Test class public class TriAngleTest { public static void main(String[] args) { TriAngle t1 = new TriAngle(3, 4); System.out.println("Area:"+t1.findArea()); } }
Summarize the sequence of attribute assignment:
- Property
- Explicit initialization
- Assignment by constructor
- Assign values by means of "object. Method" or "object. Attribute"
The above operation sequence: 1 - 2 - 3 - 4
The first three steps are called initialization because they are executed only once, while the fourth step can be executed repeatedly. In fact, the final value depends on the last decision.
Case:
- First step
-
Step 2
-
Step 3
-
Step 4
Extension 1 - JavaBean:
JavaBean is a reusable component written in JAVA language
Concept:
JavaBean s meet the following three characteristics
- Class is public
- There is a public constructor without parameters
- There are properties and get and set methods for
Purpose:
Extension 2 - UML diagram
Keyword: this
Concept:
this represents the current object
When the variable name in the formal parameter is the same as that in the attribute, the system judges that two variable names with the same name belong to the formal parameter, but if this is added before the attribute name Keyword, the system will recognize it as an object (the object can call properties and methods), and then the two with the same name can be distinguished, as shown in the figure
this modifier attribute
The "this. Attribute" is to distinguish variable names in formal parameters and classes to prevent duplication. In the class method, you can use the "**this.** attribute" or "this. method" to invoke the properties and methods of the current class. But usually choose to omit this
In particular, if the variable name in the formal parameter is the same as the variable name in the class, you must use this, otherwise the compilation will report an error
this call constructor
"this()" calls an empty parameter constructor.
public class Test01 { int num1; String name; int age; public Test01() { } //this calls the null argument constructor public Test01(int num1) { this(); this.num1 = num1; } //this calls the constructor with parameters public Test01(int num1, String name, int age) { this(num1); this.name = name; this.age = age; } }
Only one this() can be declared in a constructor, and can only be placed in the first line, and cannot coexist with the super() keyword
case
Test class
boy
gir
Keyword package
Concept:
In order to better manage classes in the project, a package is provided
Use package to declare the package to which the class or interface belongs, which is declared in the first line of the source file
The package belongs to an identifier, which needs to follow the naming rules of the identifier, (xxx.zzz.yyy) "see the meaning of the name"
every last. Is a layer of file directory
Supplement:
- Under the same package, you cannot declare an interface, class
- Under different packages, you can declare interfaces and classes with the same name
Introduction to main packages in JDK:
Package name | summary |
---|---|
java.lang | Contains some Java language core classes, such as String, Math, Integer, System and Thread, to provide common functions. |
java.net | Contains classes and interfaces that perform network related operations |
java.io | Contains classes that provide multiple input / output functions |
java.util | It contains some utility classes, such as collection framework classes that define system features and interfaces, and functions related to practical dates and calendars |
java.text | Contains some java formatting related classes |
java.sql | Contains java JDBC database programming related classes and interfaces |
java.awt | It contains several classes that make up the abstract window toolkits. These classes are used to build and manage the graphical user interface (GUI) B / s and C / s of the application |
import keyword:
use:
-
Explicitly use the import structure in the source file to import the classes and interfaces under the specified package
-
The declaration is between the declaration of the package and the declaration of the class
-
If you import multiple structures and write them out side by side
-
You can import all structures under xxx package by means of "xxx. ******"
-
Using "xxx. *" means that you can call all structures under xxx package, but if you use structures under xxx sub package, you still need to display the import.
-
If you are using Java The structure defined under the Lang package can be omitted, not imported, and automatically included
-
If the class and structure used are defined in this package, the import structure can be omitted
-
If classes with the same name under different packages are used in the source file, at least one class must be displayed with the full name
Account acct = new Account(1000); //To create an object with the same name and import a package, you need to complete the package name com.atguigu.exer3.Account acc1 = new com.atguiguexer3.Account(1000)
-
import static: imports a static structure: property or method in the specified class or interface.
//Correct, all structures are selected import static java.lang.System.*; //Wrong, the foothold should be a structure, property or method, not a class //import static java.lang.Math;
MVC design mode:
There are many classes in a project, and there are many packages according to modules. When there is a problem with the program, go to the corresponding package to fix the bug