Object oriented Foundation
1. Main line
- Java classes and their members: properties, methods, constructors; Code block, inner class
- Three characteristics of facing objects
- Encapsulation
- Inheritance
- Polymorphism
- (abstraction)
- Other keywords: this, super, static, final, abstract, interface, package, import
2. Classes and objects
class
Class is the description of a class of things, which is an abstract and conceptual definition.
-
Design a class
- Properties (member variables, fields, fields)
- Method (member function, method, method)
class Person{ //attribute String name; int age; boolean isMale; //method public void eat(){ System.out.println("having dinner"); } public void sleep(){ System.out.println("sleep"); } public void talk(String language){ System.out.println("say" + langue + "language"); } }
-
Using classes and their objects
public class Test{ public static void main(String[] args){ //Create an object of the Person class (instantiation of the class) Person p1 = new Person(); //Call the properties and methods of the object //Call properties: object Attribute name p1.name = "Tom"; p1.age = 18; p1.isMale = true; System.out.println(p1.name); //Calling method: object Method name () p1.eat(); p1.sleep(); p1.talk("Chinese"); } }
- When creating an instance of a class, you need to use the new keyword;
- Class is the abstraction of object, and object is the concrete of class;
- The object can deduce the class (reflection mechanism);
-
Properties in class
- Attribute vs local variable
- Same point
- The format defined is the same
- Declare before use
- Each has its corresponding scope
- difference:
- The position of declaration in the class is different: the attribute is directly declared in the class; Local variables are declared within methods, method parameters, code blocks, constructor parameters, or constructors
- The life cycle is different: attributes are born with the creation of objects and disappear with the demise of objects; Local variables are declared until the end of the method
- Different memory locations: attributes are allocated to the space in the heap or in the static field; Local variables allocate space in the stack
- Different scopes: attributes can use permission modifiers to control their scopes; The scope of a local variable is within a pair of braces
- The default initialization values are different: the attribute has a default initialization value (the same as the array); the local variable has no default initialization value and can be used only after it is declared
- Same point
- Attribute vs local variable
-
Methods in classes
Describes the functions of an object.
- Method declaration: permission modifier return value type method name (formal parameter list) {method body}
- Method can also use permission modifiers
- static, final, abstract modifiers
- The method name is an identifier and must follow the naming rules
- Formal parameter list: 0, 1 or more formal parameters can be declared
- Class methods can call the properties of the current class or the methods of the current class
- Methods in a class can access private properties of objects of that class
object
An object is each individual of such things that actually exist, so it is also called an instance.
public class Test{ public static void main(String[] args){ Person p1 = new Person(); p1.name = "Tom"; p1.age = 18; p1.isMale = true; System.out.println(p1.name); p1.eat(); p1.sleep(); p1.talk("Chinese"); Person p2 = new Person(); System.out.println(p2.name);//null p2.name = "Petter"; System.out.println(p2.name); } }
- Each object has its own independent memory space (except for static modified properties and methods);
- The uninitialized attribute in the class is given its default initialization value (refer to the default initialization value in the array);
- Memory parsing of object
- Heap, the only purpose of this memory area is to store object instances (here refers to objects in a broad sense: from new). Almost all object instances allocate memory here. This is described in the Java virtual machine specification: all object instances and arrays should be allocated on the heap.
- Stack refers to the virtual machine stack. The virtual machine stack is used to store local variables, etc. the local variable table stores various basic data types (boolean, byte, char, short, int, float, long, double) and object references of known length at compilation time (reference type, which is not equivalent to the object itself, but the first address of the object in heap memory). After the method is executed, it is automatically released.
- The Method Area is used to store class information, constants, static variables, code compiled by the real-time compiler and other data that have been loaded by the virtual machine.
- Instance resolution:
public static void main(String[] args){ Person p1 = new Person(); p1.name = "Tom"; p1.age = 18; p1.isMale = true; Person p2 = new Person(); sysout(p2.name);//null Person p3 = p1; p3.age = 10; }
-
object array
Example:
Class Student is defined, which contains three attributes: Student number(int), grade state(int), and grade score(int). Create 20 Student objects with Student numbers from 1 to 20. Grades and grades are determined by random numbers.
Question 1: print out the student information of grade 3 (state value is 3).
Question 2: use bubble sorting to sort students' grades and traverse all student informationpublic class Exercise4 { public static void main(String[] args) { Student[] students = new Student[20]; Exercise4 demo = new Exercise4(); demo.initStudent(students, 20); demo.searchState(students, 3); demo.sortWithScore(students); demo.printInfo(students); } /** * * @Description Initialize object array * @author zbs * @date Jul 29, 20212:36:24 PM * @param students */ public void initStudent(Student[] students, int num) { for (int i = 0; i < num; i++) { students[i] = new Student(); students[i].number = i + 1; students[i].score = (int)(Math.random() * 100) + 1; students[i].state = (int)(Math.random() * 6) + 1; } } /** * * @Description Find by grade * @author zbs * @date Jul 29, 20212:37:15 PM * @param students * @param state */ public void searchState(Student[] students, int state) { System.out.println("The third grade students are:"); System.out.println("Student number\t achievement\t grade"); for (int i = 0; i < students.length; i++) { if (students[i].state == state) { students[i].showInfo(); } } } /** * * @Description Sort according to grades * @author zbs * @date Jul 29, 20212:37:43 PM * @param students */ public void sortWithScore(Student[] students) { boolean flag; for (int i = 0; i < students.length; i++) { flag = true; for (int j = 0; j < students.length - i - 1; j++) { if (students[j].score > students[j + 1].score) { Student temp = students[j]; students[j] = students[j + 1]; students[j + 1] = temp; flag = false; } } if (flag) { break; } } } /** * * @Description Output object array information * @author zbs * @date Jul 29, 20212:38:18 PM * @param students */ public void printInfo(Student[] students) { System.out.println("The ranking from small to large is:"); System.out.println("Student number\t achievement\t grade"); for (int i = 0; i < students.length; i++) { students[i].showInfo(); } } } class Student{ /** * Student number */ int number; /** * grade */ int state; /** * fraction */ int score; public void showInfo() { System.out.print(number + "\t"); System.out.print(score + "\t"); System.out.println(state + "\t"); } }
-
How to understand that everything is an object
- In the category of Java language, we encapsulate functions and structures into classes, and call specific function structures through class instantiation;
- Custom classes and objects
- Files: File
- Network resources, URL s
- When it comes to the interaction between Java language and front-end Html and back-end database, it is embodied as classes and objects;
- In the category of Java language, we encapsulate functions and structures into classes, and call specific function structures through class instantiation;
-
Anonymous object
The created object is not received by the variable;
Anonymous objects can only be called once;
Commonly used as parameter transfer, as follows:
class Test{ public static void main(){ PhoneMall mall = new PhoneMall(); mall.show(new Phone()); //Parameter passed in anonymous object } } class PhoneMall{ public void show(Phone phone){ phone.sendMaile(); phone.playGame(); } } class Phone{ double price; public void sendEmail(){ System.out.println("Send mail"); } public void playGame(){ System.out.println("play a game"); } }
-
Exercise: Customizing tool classes for arrays
public class ArrayUtil { /** *Returns the maximum value of the array ֵ * @Description * @author zbs * @date Jul 29, 20214:25:45 PM * @param array * @return */ public static int getMax(int[] array) { int max = array[0]; for (int i = 1; i < array.length; i++) { if (array[i] > max) { max = array[i]; } } return max; } /** * Returns the minimum value of the array ֵ * @Description * @author zbs * @date Jul 29, 20214:29:13 PM * @param array * @return */ public static int getMin(int[] array) { int min = array[0]; for (int i = 1; i < array.length; i++) { if (array[i] < min) { min = array[i]; } } return min; } /** *Returns the sum of arrays * @Description * @author zbs * @date Jul 29, 20214:34:02 PM * @param array * @return */ public static int getSum(int[] array) { int sum = 0; for (int i = 0; i < array.length; i++) { sum += array[i]; } return sum; } /** * Returns the average value of the array ֵ * @Description * @author zbs * @date Jul 29, 20214:37:43 PM * @param array * @return */ public static double getAvarage(int[] array) { int sum = 0; for (int i = 0; i < array.length; i++) { sum += array[i]; } return sum/array.length; } /** * Invert array * @Description * @author zbs * @date Jul 29, 20214:41:50 PM * @param array */ public static void reverse(int[] array) { for (int i = 0; i < array.length / 2; i++) { int index = array.length - 1 - i; int temp = array[i]; array[i] = array[index]; array[index] = temp; } } /** *Copy array * @Description * @author zbs * @date Jul 29, 20214:44:02 PM * @param array * @return */ public static int[] copy(int[] array) { int[] temp = new int[array.length]; for (int i = 0; i < array.length; i++) { temp[i] = array[i]; } return temp; } /** * Bubble sorting * @Description * @author zbs * @date Jul 29, 20214:48:23 PM * @param array */ public static void bullotSort(int[] array) { boolean flag; for (int i = 0; i < array.length - 1; i++) { flag = true; for (int j = 0; j < array.length - 1 - i; j++) { if (array[j] > array[j + 1]) { int temp = array[j]; array[j] = array[j+1]; array[j+1] = temp; flag = false; } } if (flag) { break; } } } /** * Output array contents * @Description * @author zbs * @date Jul 29, 20214:50:24 PM * @param array */ public static void toString(int[] array) { System.out.print("["); for (int i = 0; i < array.length - 1; i++) { System.out.print(array[i] + ","); } System.out.print(array[array.length - 1] + "]"); } /** * Finds the location of the specified element * @Description * @author zbs * @date Jul 29, 20214:52:35 PM * @param array * @param dest * @return */ public static int getElem(int[] array, int dest) { for (int i = 0; i < array.length; i++) { if (array[i] == dest) { return i; } } return -1; } } public class ArrayUtilTest { public static void main(String[] args) { int[] array = {1, 3, 5, 7, 9, 2, 4, 6, 8, 10}; ArrayUtil.bullotSort(array); ArrayUtil.toString(array); } }
3. Method overload
heavy load
-
Concept: 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.
-
Only the following three cases are overloaded:
- Different parameter types
- Different number of parameters
- The order of parameters is different
- Overloading is only related to the number and type of parameters in the parameter list, not to the parameter name and return value type;
- The order of parameters is also overloaded;
- When there are overloaded methods, match from low-level types;
-
How to determine which method an object calls: method name - > parameter list
Value Passing Mechanism of method parameters
-
What is an assignment operation
-
For basic data types:
int m = 10; int n = m; System.out.println("m = " + m + ", n = " + n);//m = 10, n = 10 n = 20; System.out.println("m = " + m + ", n = " + n);//m = 10, n = 20
In the process of basic data type assignment, the value is copied and assigned to a new variable. That is, there are two copies of the same value in memory.
-
For reference data types:
class Order{ int orderId; } class Test{ public static void main(String[] args){ Order o1 = new Order(); o1.orderId = 1001; Order o2 = o1; System.out.println("o1.orderId = " + o1.order + ", o2.orderId = " + o2.orderId); //o1.orderId = 1001, o2.orderId = 1001 o2.orderId = 1002; System.out.println("o1.orderId = " + o1.order + ", o2.orderId = " + o2.orderId); //o1.orderId = 1002, o2.orderId = 1002 } }
The assignment of a reference data type is to assign an address to a new variable. That is, two variables point to the same memory space.
-
-
Transfer mechanism of formal parameters
-
pass by value
class Test { public static void main(String[] args){ int a = 10; int b = 20; System.out.println("a = " + a + ", b = " + b);//a = 10, b = 20 Test test = new Test(); test.swap(a, b); System.out.println("a = " + a + ", b = " + b);//a = 10, b = 20 } public void swap(int m, int n){ int temp = m; m = n; n = temp; } }
Execution result: two values exchange failed.
Execution process:
-
Firstly, two variables a and b are defined in the main method, and two formal parameters m and n and the local variable temp are defined in the swap() function.
-
Then pass the arguments a and b to the formal parameters in the swap() function, which is equivalent to the execution of m = a;, Since the assignment operation of n = b is a basic data type, the memory addresses of a, b, m and N are not the same.
-
Then, in the swap() function, the values of m and n are exchanged through the temp variable, but it has no effect on the values of a and b.
-
After the function is executed, the memory space of formal parameters and local variables is released, which does not have the effect of exchanging a and b.
Memory map:
-
-
Address transfer
class Data{ int a; int b; } class Test { public static void main(String[] args){ Data data = new Data(); int data.a = 10; int data.b = 20; System.out.println("a = " + data.a + ", b = " + data.b);//a = 10, b = 20 Test test = new Test(); test.swap(data); System.out.println("a = " + a + ", b = " + b);//a = 20, b = 10 } public void swap(Data data){ int temp = data.a; data.a = data.b; data.b = temp; } }
Execution result: exchange succeeded
Execution process:
- Encapsulate the two numbers to be exchanged in the Data class, create the object of this class in the main method and initialize it.
- Pass the data object as the parameter of the swap() function into the method;
- Because data is a reference data type, address passing is used to pass the address of the data object into the method, that is, the memory space pointed to by data in the swap() method is the same as that pointed to by data in the main method.
- Therefore, exchanging values in the swap() function is equivalent to exchanging values for data in the main method.
Memory map:
-
Summary:
- If the parameter is a basic data type, the change of the formal parameter in the function does not affect the value of the actual parameter outside the function;
- If the parameter is a reference data type, the change of the formal parameter in the function affects the value of the argument outside the function.
-
Variable number of formal parameters
Allows you to directly define formal parameters that can match multiple arguments.
-
Format of parameter definition: data type Variable name
-
usage method:
class Test{ public static void main(String[] args){ Test test = new Test(); test.show(1); test.show("hello", "world"); //Pass in variable parameters } public void show (int num){ System.out.println("show(int)"); } public void show(String ... strs){ //Define variable parameters System.out.println("show(String ...)"); for (int i = 0; i < strs.length; i++){ System.out.println(strs[i]); } } }
-
Notes:
- The form of variable parameters can be overloaded with other methods with the same name;
- Methods with the same name as variable parameters and array parameters cannot exist at the same time;
- Variable parameters are actually arrays;
- Variable parameters should be at the end of the parameter list and can only be declared;
4. Encapsulation
The pursuit of programming: high cohesion and low coupling
- High cohesion: the data operation details inside the class are completed by themselves, and external interference is not allowed;
- Low coupling: only a small amount of methods are exposed for use;
Encapsulation is to hide what should be hidden and expose what should be exposed.
public class Test{ public static void main(String[] args){ Animal animal = new Animal(); animal.name = "yolk"; animal.age = -2;//Incorrect assignment animal.setAnimal(-2); animal.show(); System.out.println("age: " + animal.getAge()); } } class Animal{ String name; private int age;//Add an access modifier to constrain the age variable //age is judged and assigned by method public setAge(int age1){ if (age > 0 && age < 100){ age = age1; } else { age = 0; } } //Provide access methods for inaccessible properties public int getAge(){ return age; } public void show(){ System.out.println("name: " + name + ", age: " + age); } }
Questions raised:
After we create an object of a class, we can assign values to the attributes of the object by means of "object. Attribute". Here, the assignment operation is restricted by the data type and storage range of the attribute. In addition, there are no other constraints. However, in practical problems, we often need to add additional constraints to attribute assignment. This condition cannot be reflected in the attribute declaration. We can only add constraints through methods. (for example: setAge()). At the same time, we need to prevent users from assigning attributes in the way of "object. Attribute". You need to declare the attribute private.
Embodiment of encapsulation:
-
We privatize the property xxx of the class and provide a public method to get (getXxx) and set (setXxx) the value of this property
Expansion: embodiment of encapsulation: ① above ② private method without external exposure ③ singleton mode -
Access modifier
Within class This package Non buns subclass Non package non subclass public √ √ √ √ default √ √ √ × protected √ √ × × private √ × × × It can be used to modify classes and their internal structures, properties, methods, constructors and internal classes;
Class can only be decorated with public or default;
private limits that properties or methods cannot be accessed outside the class, but can be accessed inside the class.
5. Constructor
Any class has at least one constructor
- Function of constructor:
-
create object
String str = new String(); //new + constructor
-
Initialize object
String str = new String("lhp"); //Initialize str = "lhp"
-
Constructor definition: permission control modifier class name (formal parameter list) {method body}
Constructors are different from methods;
The constructor name must have the same name as the class name;
Constructor has no return value;
Multiple constructors can be defined in a class, which conforms to the rules of method overloading;
Once the class constructor is defined in the displayed, the system will no longer provide the default null parameter constructor;
The permissions of the default constructor are the same as those of the class;
Callable methods and constructors in constructors;
6. this keyword
public class Test{ Person p1 = new Person(); p1.setAge(19); System.out.println(p1.getAge()); /* If the constructor is ignored: * case1: Output 0 * case2: Output 19 */ } class Person{ private String name; private int age; public Person(){ } public Person(String name){ this.name = name; } public Person(int age){ this.age = age; } public Person(String name, int age){ //Call the null argument constructor this(); //Call constructor with parameters this(name); this(name, age); this.name = name; this.age = age; } public void setName(String name){ //case1: name = name; //case2: this.name = name; } public void setAge(int age){ //case1: age = age; //case2: this.age = age; } public String getName(){ return this.name; } public int getAge(){ return this.age; } }
thsi modifier properties and methods:
- this can be understood as the current object
- In the method of the class, you can use "this. Property" or "this. Method" to call the property or method of the current object. In general, this can be omitted. In special cases, if the method's shape participating attribute or method has the same name, the keyword this must be added to indicate that it is the attribute of the current object, not the formal parameter.
- In the constructor of the class, we can call the object property or method currently being created by using "this. Property" or "this. Method". However, usually, we choose to omit "this.". In special cases, if the formal parameter of the constructor has the same name as the attribute of the class, we must explicitly use the "this. Variable" to indicate that the variable is an attribute, not a formal parameter.
this modifier constructor:
- In the class constructor, we can explicitly use the "this (formal parameter list)" method to call other constructors specified in this class
- Constructor cannot call itself through "this (formal parameter list)"
- If there are n constructors in a class, "this (formal parameter list)" is used in up to n - 1 constructors
- Specifies that "this (formal parameter list)" must be declared on the first line of the current constructor
- Inside the constructor, at most one "this (formal parameter list)" can be declared to call other constructors
practice:

public class Test{ public static void main(String[] args) { Boy boy = new Boy("zbs", 20); Girl girl = new Girl("lhp", 19); boy.marry(girl); girl.marry(boy); } } class Boy{ private String name; private int age; public Boy(){ } public Boy(String name){ this.name = name; } public Boy(int age){ this.age = age; } public Boy(String name, int age){ this.name = name; this.age = age; } public void setName(String i){ name = i; } public String getName(){ return this.name; } public void setAge(int i){ age = i; } public int getAge(){ return this.age; } public void marry(Girl girl){ System.out.println("I want to marry" + girl.getName()); } public void shout(){ if (this.age >= 22){ System.out.println("You can get married"); } else { System.out.println("Wait a minute"); } } } class Girl{ private String name; private int age; public Girl(){ } public Girl(String name){ this.name = name; } public Girl(int age){ this.age = age; } public Girl(String name, int age){ this.name = name; this.age = age; } public void setName(String i){ name = i; } public String getName(){ return this.name; } public void marry(Boy boy){ System.out.println("I want to marry" + boy.getName()); boy.marry(this); } /** * @Description Compare the size of two objects * @author zbs * @date Jul 29, 20212:38:18 PM * @param girl * @return Positive number: the current object is large; Negative: the current object is small; 0: the current object is equal to the parameter object */ public void compare(Girl girl){ return this.age - girl.age; } }
7. JavaBean
JavaBean s are reusable components written in the Java language.
JavaBean s refer to Java classes that meet the following standards:
- Class is public;
- There is a parameterless constructor;
- There are attributes and corresponding get and set methods;
public class Customer{ //attribute private int id; private String name; //Null parameter constructor public Customer (){ } //get, set methods public void setId(int id){ this.id = id; } public void setName(String name){ this.name = name; } public int getId(){ return id; } public String getName(){ return name; } }
8. UML class diagram
9. package keyword
-
Using package can better realize project management.
-
Use package to declare the package to which the class or interface belongs, and put it on the first line of the source file.
-
The package name is an identifier and follows the naming rules.
-
Each point in the registration represents a file directory.
Interfaces and classes with the same name cannot be named under the same package; Interfaces and classes with the same name can be named under different packages
10. import keyword
Use the import keyword 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;
You can import multiple structures and write them out side by side;
You can use = =*== All structures under the specified package can be imported in the way of;
java. The structure under Lang package has been imported by default, and common classes such as Sting and System are placed in it;
If the class or interface used is under this package, the import structure can be omitted;
If a class with the same name under different packages is used in the source file, the full class name shall be used;
The package imported with import can only use the classes under the current package, while the classes in the sub packages under the current package cannot be used and need to be imported;
Import static can import static structures in classes or interfaces;
11. MVC design mode
experiment
-
Create corresponding classes and provide necessary structures according to the following UML class diagram
In the withdrawal method withdraw(), you need to judge whether the user's balance can meet the withdrawal amount requirements. If not, you should give a prompt. The deposit() method represents a deposit.
-
Create corresponding classes and provide necessary structures according to the following UML class diagram
-
Create corresponding classes and provide necessary structures according to the following UML class diagram
-
The addCustomer method must construct a new customer object according to the parameters (last name, first name) and put it into the customer array. It must also add 1 to the value of the numberOfCustomer property.
-
The getNumOfCustomers method returns the value of the numberofCustomers property.
-
The getCustomer method returns the customer associated with the given index parameter.
-
-
Create a BankTest class to test.
public class Account{ private double balance; public Account(double init_balance){ this.balance = init_balance; } public double getBalance(){ return this.balance; } public void deposit(double amt){ if (amt >= 0){ balance += amt; sysout("Save money successfully!"); } else { sysout("The amount of money saved cannot be negative!!"); } } public void withdraw(double amt){ if (balance >= amt){ balance -= amt; sysout("Withdrawal succeeded!"); } else { sysout("Insufficient balance, withdrawal failed!"); } } }
public class Customer{ private String firstName; private String lastName; private Account account; public Customer(String f, String l){ this.firstName = f; this.lastName = l; } public String getFirstName(){ return this.firstName; } public String getLastName(){ return this.lastName; } public Account getAccount(){ return this.account; } public void setAccount(Account acct){ this.account = acct; } }
public class Bank{ private Customer[] customers; private int numberOfCustomer; public Bank(){ customers = new Customer[10]; } public addCustomer(String f, String l){ customers[numberOfCustomer++] = new Custemou(f, l); } public int getNumOfCustomers(){ return this.numberOfCustomer; } public Customer getCustomer(int index){ if (index < numberOfCustomer && index >= 0){ return this.customers[index]; } return null; } }
public class Test{ public static void main(String[] args){ Bank bank = new Bank(); bank.addCustomer("zhao", "binsheng"); bank.getCustomer(0).setAccount(new Account(2000)); bank.getCustomer(0).getAccount().withdraw(500); double balance = bank.getCustomer(0).getAccount().getBalance(); System.out.println("customer:" + bank.getCustomer(0).getFirstName() + "The account balance is:" + balance); } }