Three main lines of learning object-oriented content
1.Java classes and class members: properties, methods and constructors; Code block, inner class
2. Three characteristics of object-oriented: encapsulation, inheritance, polymorphism, (abstraction)
3. Other keywords: this, super, static, final, abstract, interface, package, import, etc
Principle: "focus on the big, start with the small"
1, Process oriented and object oriented
Example: "people put elephants in the refrigerator"
1. Process oriented: it emphasizes the functional behavior, taking the function as the minimum unit and considering how to do it.
① Open the refrigerator door
② Lift the elephant and stuff it into the fridge
③ Close the refrigerator door
2. Object oriented: emphasize the objects with functions, take the class / object as the minimum unit, and consider who will do it.
People{
Open (refrigerator){
Refrigerator. Open ();
}
Lift (an elephant){
Elephant. Enter (refrigerator);
}
Turn off (refrigerator){
Refrigerator. Closed ();
}
}
Refrigerator{
Open () {}
Close () {}
}
Elephant{
Enter (refrigerator){
}
}
2, Java basic elements: classes and objects
Class: the description of a class of things, which is an abstract and conceptual definition
Object: it is each individual of such things that actually exists, so it is also called instance
> It can be understood as: class = abstract concept; object = real person
> Object oriented programming focuses on class design
> A design class is a member of a design class
Attribute = member variable = field = field, field
Method = member method = function = method
Use of classes and objects (implementation of object-oriented ideas):
1. Create a class and design the members of the class
2. Create class objects
3. Call the structure of the object through "object. Attribute" or "object. Method"
3, Object creation (new) and use (.)
Object to create class = instantiation of class = instantiation of class
Structure of calling object: attribute and method
Calling property: "object. Property"
Calling method: "object. Method"
If multiple objects of a class are created, each object has a set of class properties independently. (non static)
This means that if we modify attribute a of one object, the value of attribute a of another object will not be affected.
Memory resolution of object:
After compiling the source program, it is transformed into one or more bytecode files.
We use the class loader and interpreter in the JVM to interpret and run the generated bytecode file, which means that the class corresponding to the bytecode file needs to be loaded into memory, involving memory parsing. (memory parsing is performed at runtime!)
heap: store instances of objects, such as all new things and arrays
Stack: the stack we often say in java usually refers to the virtual machine stack, which is used to store local variables
Method area: store the loaded class information, constants and static variables
A test code for the Person class
public class PersonTest { public static void main(String[] args) { //Create an object of the Person class Person p1 = new Person(); Person p2 = new Person(); //Similar to Scanner scanner = new Scanner(System.in); p1.name = "Tom"; p1.isMale = true; System.out.println(p1.name); p1.eat(); p1.sleep(); p1.talk("Chinese"); System.out.println(p2.name); System.out.println(p2.isMale); Person p3 = p1; System.out.println(p3.name); p3.age = 10; System.out.println(p1.age); } } class Person{ //attribute String name; int age = 1; boolean isMale; //method public void eat() { System.out.println("People can eat"); } public void sleep() { System.out.println("People can sleep"); } public void talk(String language) { System.out.println("People can speak, saying:" + language); } }
4, One of the members of the class: properties
* Use of properties in class
*
* Properties (member variables) vs local variable
* 1. Similarities:
* one point one Defining the format of variables: data types Variable name = variable value
* 1.2 declaration before use
* 1.3 each variable has its corresponding scope
*
* 2. Differences:
* 2.1 different positions declared in classes
* Attribute: directly defined in a pair of {} of the class
* Local variables: variables declared within methods, method parameters, code blocks, constructor parameters, and constructors
*
* 2.2 differences on permission modifiers
* Attribute: when declaring an attribute, you can specify its permission and use the permission modifier.
* Common permission modifiers: private, public, default, protected ---> Encapsulation
* At present, when you declare properties, you can use the default.
* Local variables: permission modifiers are not allowed.
*
* 2.3 default initialization value:
* Attribute: the attribute of a class has a default initialization value according to its type.
* Integer (byte, short, int, long): 0
* Floating point (float, double): 0.0
* char: 0 (or '\ u0000')
* boolean: false
*
* Reference data type (class, array, interface): null
*
* Local variable: no default initialization value.
* This means that we must explicitly assign values before calling local variables.
* In particular: when the formal parameter is called, we can assign a value.
*
* 2.4 loading location in memory:
* Properties: load into heap space (non static)
* Local variables: loading into stack space
Test code -- UserTest
public class UserTest { public static void main(String[] args) { User u1 = new User(); System.out.println(u1.name); System.out.println(u1.name); System.out.println(u1.name); } } class User{ String name; int age; boolean isMale; public void talk(String language) { System.out.println("We use" + language + "Communicate"); } public void eat() { String food = "Flapjack"; System.out.println("Northerners like to eat: " + food); } }
5, Class member 2: method
Declaration and use of methods in classes
Method: describe the function that the class should have.
For example:
Math class: sqrt()\random() \
Scanner class: nextXxx()
Arrays class: sort() \ binarySearch() \ toString() \ equals() \
Shortcut keys:
Ctrl + Shift + t
Ctrl + o
1. Examples:
public void eat(){}
public void sleep(int hour){}
public String getName(){}
public String getNation(String nation){}
2. Method declaration: permission modifier Return value type Method name (formal parameter list){
Method body
}
Note: the methods modified by static, final and abstract will be described later.
3. Description:
3.1 about permission modifiers: the permission modifiers of the default method use public first
There are four kinds of permission modifiers specified by Java: private, public, default and protected --> More details on encapsulation
3.2 return value type: with return value vs has no return value
3.2.1 If a method has a return value, the type of the return value must be specified when the method is declared. At the same time, in the method, You need to use the return keyword to return a variable or constant of the specified type: "return data".
If the method has no return value, it is represented by void when the method is declared. Typically, there are no methods that return values You don't need to use return in. However, if you use it, only "return;" means to end this method
3.2.2 do we define whether the method should have a return value?
① Look at the topic requirements ② Based on experience: specific analysis of specific problems
3.3 method name: it belongs to the identifier and follows the rules and specifications of the identifier, "see name and meaning"
3.4 formal parameter list: methods can declare 0, 1, or more formal parameters.
3.4.1 format: data type 1, parameter 1, data type 2, parameter 2
3.4.2 should we define formal parameters when defining methods?
① Title Requirements ② Based on experience: specific analysis of specific problems
3.5 method body: the embodiment of method function.
4. Use of return keyword:
1. Scope of application: used in the method body
2. Function: ① end method
② For methods with return value types, use the "return data" method to return the required data.
3. Note: you cannot declare an execution statement after the return keyword.
5. In the use of methods, you can call the properties or methods of the current class
Special: method A: recursive method is called in method A.
Method cannot be defined!!!.
Test code -- CustomerTest
public class CustomerTest { public static void main(String[] args) { Customer cust1 = new Customer(); cust1.eat(); cust1.sleep(8); } } class Customer{ String name; int age; boolean isMale; public void eat() { System.out.println("Customers eat"); return;//This indicates the end of the method //You cannot declare an expression after return // System.out.println("hello"); } public void sleep(int hour) { System.out.println("rest" + hour +"Hours"); eat(); // sleep(10); } public String getname() { if (age > 18) { return name; }else { return "Tom"; } } public String getNation(String nation) { String info = "My nationality is:" + nation; return info; } public void info(){ //You cannot define another method in a method // public void swim() { // // } } }
Exercises
1.1 create a Person class
public class Person { String name; int age; /** * sex:0 Indicates that it is female * sex:1 Indicates that it is male * */ int sex; public void study() { System.out.println("studying"); } public void showAge() { System.out.println("age: " + age); } public int addAge(int i) { age += i; return age; } }
1.2 create a PersonTest class
public class PersonTest { public static void main(String[] args) { Person p1 = new Person(); p1.name = "Tom"; p1.age = 18; p1.sex = 1; p1.study(); p1.showAge(); int newAge = p1.addAge(2); System.out.println(p1.name + "The new age is:" + newAge); System.out.println(p1.age); Person p2 = new Person(); p2.showAge(); p2.addAge(10); p2.showAge(); p1.showAge(); } }
public class CircleTest { public static void main(String[] args) { Circle c1 = new Circle(); c1.radius = 3.1; //Corresponding method I: // double area = c1.findArea(); // System.out.println(area); c1.findarea(); } } class Circle{ double radius; //Find the area of a circle //Mode 1: // public double findArea() { // double area = Math.PI * radius * radius; // return area; // } // Mode 2: public void findarea() { double area = Math.PI * radius * radius; System.out.println("Area:" + area); } }
public class Exer3Test { public static void main(String[] args) { Exer3Test test = new Exer3Test(); //3.1 testing // test.method(); //3.2 testing //Mode 1: // int area = test.method(); // System.out.println("area:" + area); //Mode 2: // System.out.println(test.method()); //3.3 testing int area = test.method(12, 10); System.out.println("Area:" + area); } // 3.1 // public void method() { // for (int i = 0; i < 10; i++) { // for (int j = 0; j < 8; j++) { // System.out.print("* "); // } // System.out.println(); // } // } //3.2 // public int method(){ // for (int i = 0; i < 10; i++) { // for (int j = 0; j < 8; j++) { // System.out.print("* "); // } // System.out.println(); // } // // return 10 * 8; // } //3.3 public int method(int m, int n) { for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { System.out.print("* "); } System.out.println(); } return m * n; } }
public class StudentTest { public static void main(String[] args) { //Declare an array of Student type Student[] stus = new Student[20]; for (int i = 0; i < stus.length; i++) { //Assign values to array elements stus[i] = new Student(); //Assign a value to the property of the Student object stus[i].number = i + 1; //Hypothetical grade: [1, 6] stus[i].state = (int)(Math.random() * (6 -1 + 1) + 1); //Score: [0, 100] stus[i].score = (int)(Math.random() * (100 - 0 + 1) + 0); } //Traverse student array for (int i = 0; i < stus.length; i++) { // System.out.println(stus[i].number + "," + stus[i].state + "," + stus[i].score); System.out.println(stus[i].info()); } System.out.println("*************"); //Question 1: print out the student information of grade 3 (state value is 3). for (int i = 0; i < stus.length; i++) { if (stus[i].state == 3) { System.out.println(stus[i].info()); } } System.out.println("###########"); //Question 2: use bubble sorting to sort students' grades and traverse all student information for (int i = 0; i < stus.length - 1; i++) { for (int j = 0; j < stus.length - 1 - i; j++) { if (stus[j].score > stus[j+1].score) { Student temp = stus[j]; stus[j] = stus[j + 1]; stus[j + 1] = temp; } } } for (int i = 0; i < stus.length; i++) { System.out.println(stus[i].info()); } } } class Student{ int number; //Student number int state; int score; //Method of displaying student information public String info() { return "Student No.:" + number + ",Grade:" + state + ",Achievement:" + score; } }
Code improvement: encapsulate the function of operating array into method
public class StudentTest2 { public static void main(String[] args) { // Declare an array of Student type Student2[] stus = new Student2[20]; for (int i = 0; i < stus.length; i++) { // Assign values to array elements stus[i] = new Student2(); // Assign a value to the property of the Student object stus[i].number = i + 1; // Hypothetical grade: [1, 6] stus[i].state = (int) (Math.random() * (6 - 1 + 1) + 1); // Score: [0, 100] stus[i].score = (int) (Math.random() * (100 - 0 + 1) + 0); } StudentTest2 test = new StudentTest2(); // Traverse student array test.print(stus); System.out.println("*************"); // Question 1: print out the student information of grade 3 (state value is 3). test.searchState(stus, 3); System.out.println("###########"); // Question 2: use bubble sorting to sort students' grades and traverse all student information test.sort(stus); test.print(stus); } /** * @Title: print * @Description: Operation of traversing Student2 [] array * @param stus Array to traverse * @return void Return type */ public void print(Student2[] stus) { for (int i = 0; i < stus.length; i++) { // System.out.println(stus[i].number + "," + stus[i].state + "," + stus[i].score); System.out.println(stus[i].info()); } } /** * * @Title: searchState * @Description: Find the information of the specified grade in the Student2 [] array * @param stus Array to find * @param state Grade you are looking for * @return void Return type */ public void searchState(Student2[] stus, int state) { for (int i = 0; i < stus.length; i++) { if (stus[i].state == state) { System.out.println(stus[i].info()); } } } /** * * @Title: sort * @Description: Sort Student2 [] array * @param stus Array to sort * @return void Return type */ public void sort(Student2[] stus) { for (int i = 0; i < stus.length - 1; i++) { for (int j = 0; j < stus.length - 1 - i; j++) { if (stus[j].score > stus[j + 1].score) { Student2 temp = stus[j]; stus[j] = stus[j + 1]; stus[j + 1] = temp; } } } } } class Student2 { int number; // Student number int state; int score; // Method of displaying student information public String info() { return "Student No.:" + number + ",Grade:" + state + ",Achievement:" + score; } }
Supplement: implementation of bubble sorting algorithm
/* * Implementation of array bubble sorting * */ public class BubbleSort { public static void main(String[] args) { int[] arr = new int[] {12,35,35,79,-56,-35,88,20,0,21}; //Bubble sorting for(int i = 0; i < arr.length - 1; i++) { for (int j = 0; j < arr.length - 1 - i; j++) { if(arr[j] > arr[j + 1]) { int temp = arr[j]; arr[j] = arr[j + 1]; arr[j + 1] = temp; } } } for (int i = 0; i < arr.length; i++) { System.out.print(arr[i] + "\t"); } } }
Review questions:
1. What are the three main lines of object-oriented programming?
① Classes and class members: properties, methods, constructors; code blocks, internal classes
② Three characteristics of object-oriented: encapsulation, inheritance and polymorphism
③ Other keywords: this,super,abstract,interface,static,final,package,import
Object oriented programming idea?
(class, object; three characteristics of object-oriented (encapsulation, inheritance and polymorphism);.)
2. Talk about your understanding of classes and objects in object-oriented, and point out the relationship between them
Class: abstract, conceptual content
Object: an entity that really exists.
An object is derived from a class (new). (an object is an instantiation of a class)
3. Embodiment of object-oriented thought I: what are the three steps to create and execute classes and objects?
① Create class
② Class instantiation
③ Structure of calling object: "object. Property" "object. Method"
4. Draw the memory allocation of the following code during execution
class Car{
String color = "red";
int num = 4;
void show(){
int a = 10;
System.out.println("color="+color+",num="+num);
}
}
class CarTest {
public static void main(String[] args) {
Car c1 = new Car();
Car c2 = new Car();
c1.color = "blue";
c1.show();
c2.show();
}
}
5. Can variables be defined in class methods? Can attributes be called? Can methods be defined? Can methods be called?
Yes; yes; no; yes
6. Ideas for completing a project (or function):
7. Classification of regression variables:
Method 1: by data type
Method 2: according to the position declared in the class
Understand "everything is an object"
1. In the category of Java language, we all encapsulate functions and structures into classes, and call specific function structures through class instantiation
> Scanner, string, etc
> Files: File
> Network resource: URL
2. When it comes to the interaction between the Java language and the front-end Html and back-end databases, the front and back-end structures are embodied as classes and objects at the Java level.
Description of memory parsing
1. Variables of reference type can only store two types of values: null Or Address value (including the type of variable)
Use of anonymous objects
1. Understanding: the object we created is not explicitly assigned to a variable name. That is, it is an anonymous object
2. Feature: anonymous objects can only be called once.
3. Use:
public class Instance { public static void main(String[] args) { Phone p = new Phone(); // p = null; System.out.println(p); p.sendEmail(); p.playGames(); //Anonymous object // new Phone().sendEmail(); // new Phone().playGames(); new Phone().price = 1999; new Phone().showPrice();//0.0 System.out.println("**********"); PhoneMall mall = new PhoneMall(); //For the use of anonymous objects, the address value is actually assigned to the formal parameter phone //At this time, the same object is called mall.show(new Phone()); } } class PhoneMall{ public void show(Phone phone) { phone.sendEmail(); phone.playGames(); } } class Phone{ double price; public void sendEmail() { System.out.println("send emails"); } public void playGames() { System.out.println("play a game"); } public void showPrice() { System.out.println("The price of mobile phone is:" + price); } }
Encapsulation of tool class:
1.1 tool ArrayUtil
public class ArrayUtil { // Find the maximum value of the array public int getMax(int[] arr) { int maxValue = arr[0]; for (int i = 1; i < arr.length; i++) { if (maxValue < arr[i]) { maxValue = arr[i]; } } return maxValue; } // Find the minimum value of the array public int getMin(int[] arr) { int minValue = arr[0]; for (int i = 1; i < arr.length; i++) { if (minValue > arr[i]) { minValue = arr[i]; } } return minValue; } // Sum arrays public int getSum(int[] arr) { int sum = 0; for (int i = 0; i < arr.length; i++) { sum += arr[i]; } return sum; } // Average the array public int getAvg(int[] arr) { return getSum(arr) / arr.length; } // Flip array public void reverse(int[] arr) { for (int i = 0; i < arr.length / 2; i++) { int temp = arr[i]; arr[i] = arr[arr.length - i - 1]; arr[arr.length - i - 1] = temp; } } // Copy array public int[] copy(int[] arr) { int[] arr1 = new int[arr.length]; for (int i = 0; i < arr1.length; i++) { arr1[i] = arr[i]; } return arr1; } // Array sorting public void sort(int[] arr) { // Bubble sorting for (int i = 0; i < arr.length - 1; i++) { for (int j = 0; j < arr.length - 1 - i; j++) { if (arr[j] > arr[j + 1]) { int temp = arr[j]; arr[j] = arr[j + 1]; arr[j + 1] = temp; } } } } // Traversal array public void print(int[] arr) { for (int i = 0; i < arr.length; i++) { System.out.print(arr[i] + "\t"); } System.out.println(); } // Find the specified element public int getIndex(int[] arr, int dest) { // Linear lookup: for (int i = 0; i < arr.length; i++) { if (dest == arr[i]) { return i; } } return -1; //Returns a negative number indicating that it was not found } }
1.2 tool class test ArrayUtilTest
public class ArrayUtilTest { public static void main(String[] args) { ArrayUtil util = new ArrayUtil(); int[] arr = new int[]{32,20,5,-8,0,99,5,-899}; int max = util.getMax(arr); System.out.println("The maximum value is:" + max); // System.out.println("before sorting:"); // util.print(arr); // // util.sort(arr); // // System.out.println("after sorting:"); // util.print(arr); // // System.out.println("find:"); int index = util.getIndex(arr, -5); if (index >= 0) { System.out.println("Found, index address:" + index); }else { System.out.println("Can't find"); } } }
6, Talk about methods again
Method overload loading...
1. Definition: 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.
"Two same and different": the same class and the same method name
Different parameter lists: different parameter numbers and different parameter types
2. Examples:
Overloaded sort() / binarySearch() in Arrays class
3. Judge whether it is overloaded:
It has nothing to do with the permission modifier, return value type, formal parameter variable name and method body of the method!
4. How to determine a specified method when calling a method through an object:
Method name -- > parameter list
7, OOP feature 1: encapsulation and hiding
8, Class member 3: constructor
9, Keyword: this
10, Keywords: package, import