Chapter 1 object oriented programming
Object oriented development process
Basic Object Oriented Analysis (OOA)
Object Oriented Design (OOD)
Object Oriented Programming (OOP)
Process oriented and object-oriented
Process oriented development: the system is designed according to the development order of things, and each process is embodied by functions (c language, the core is functions)
Object oriented development: classify the things existing in the system and reflect them according to categories (java language, the core is objects)
Supermarket system:
Facing process: 1. Log in to the system 2. Customers buy 3. cashier 4. Purchase goods 5. Exit Xiaohong supermarket to buy apples and pay
Object oriented: 1. Customer class 2. Merchant class 3. Commodity class 4. Settlement order
Thinking: Gobang game: white square and black square chessboard system
Advantages of object orientation
1. The biggest advantage is: code reuse (avoid code redundancy)
2. Different analysis can be implemented in different ways
Object oriented core
The core of object-oriented is class (object)
Class: the abstraction of a class of things, generalization, unified statement, stationery, abstract statement
Object: actual individual stationery box, specific things
Class: class is an abstract expression of object, which does not occupy memory. It is abstract when analyzing and writing code
Object: object is the materialization of a class. It occupies memory and needs to be put into a specific object
be careful:
First plan out the class, design the characteristics and behavior of the class, and create the objects of the class in the future
Composition of classes
attribute
Used to describe the characteristics of a class of things, such as student number, gender, age
method
Used to describe the behavior, action and ability of a class of things. For example, students eat, study, exercise
Syntax rules of class:
Control authority class Class name{ //attribute //method }
be careful:
- Control permission public is not added; There is only one with public, which is the same as the file name
- Class declares the keyword of the class
- Class name: Legal identifier initial capital meaning cannot be keyword
Syntax rules for attributes:
Control authority Data type attribute name [=Initial value];
be careful:
- Control permission public
- Data type: Basic + reference type
- Attribute name: the same as variable name
- The attribute can be given an initial value or not, and has a default value: int 0 double 0.0 char \u0000 boolean false reference null
Grammar rules of method: (emphasis)
Control authority [Modifier ] Return type method name(Parameter type parameter variable,Parameter type parameter variable){ Method body; [return Return value]; }
be careful:
-
Control permission public
-
Return type:
-
There is a return type. Specify a type: int double String;
return can only have one value, which is returned to the caller
-
No return type void
-
-
Method name is the same as variable name
-
Method parameters:
- When a method is declared, the external data of formal parameters must be specified one by one
- Method call time arguments
public class Student { //attribute public int sno ;//Student number public String sName;//full name public int age = 20; //Age public double weight; //weight /** * having dinner */ public void eat() { System.out.println(sName + "be at table"); } /** * Run: return to mileage */ public int run() { System.out.println(sName + "Running"); //return "km:" + 10 + "; calories:" + 300; return 10; } /** * Arithmetic problem */ public int calc(int a,int b) { return a + b; } }
Exercise: define an animal class
Attribute: name, age, variety
method:
1. Sleep: return to sleep for a few hours
2. Eating: import the food and return how many grams you ate
3. Running: no parameters, no return
public class Animal { public String name; public int age; public String type; public double sleep() { return 10; } public double eat(String food) { System.out.println(name + "eat" + food); //Return to eat return 5.5; } public void run() { System.out.println(name + "Running"); } }
Class diagram
package com.qf.oop; public class Player { public char gender;//Gender public String name;//Role name public int level; //Grade //Keyboard keys walk, and the speed is determined according to gender public String run(char code) { //Determine speed double speed = 0; if(gender == 'male') { speed = 60; } else if(gender == 'female') { speed = 40; } //Determine direction if(code == 'a') { return name + "Left by" + speed + "Speed run"; }else if(code == 's') { return name + "Down with" + speed + "Speed run"; }else if(code == 'd') { return name + "Right to" + speed + "Speed run"; }else if(code == 'w') { return name + "Up with" + speed + "Speed run"; }else { return name + "Stay where you are"; } } //Attack, incoming weapon public void fight(String weapon) { System.out.println(name + "use" + weapon + "battle"); } }
Object creation
Classes are only analyzed from the perspective of design. If you use classes, you must create objects of this class, real object instances (open up memory in the heap)
Class name object name = new Class name();
Player monkey = new Player();
When a class creates an object, it opens up memory in the heap, decides to open up according to the number of attributes defined in the class, and allocates all attributes in the heap.
Access to object members
Members: properties and methods
Property call:
Object name.Attribute name //obtain Object name.Attribute name = value; //assignment
Method call:
Data type return value = Object name.Method name(Argument 1,Argument 2...);//**Method with return value** Object name.Method name(Argument 1,Argument 2...); //no return value
be careful:
-
When calling a method, if the method in the class has formal parameters set, the actual parameters are passed in when calling
Formal parameters: parameters defined by method declarations in classes. Formal parameters are variables
Argument: the parameter when the object calls the method. The argument is a value
Arguments assign values to formal parameters, formal parameters = arguments; The number is the same, the type is the same, and the order is the same
-
When the return value is set inside the method, return the value to the location of the calling method, and the calling location needs to receive the return value
//Define location in class //weapon is a formal parameter public void fight(String weapon) { System.out.println(name + "use" + weapon + "battle"); } //Object call location monkey.fight("Golden cudgel");//Argument
Player test class:
public class TestPlayer { public static void main(String[] args) { //Create player object Player monkey = new Player(); //System.out.println(monkey);// address //System.out.println(monkey.name);//null //System.out.println(monkey.level);//0 //System.out.println(monkey.gender);//\u0000 monkey.name = "Monkeyking"; monkey.level = 2; monkey.gender = 'male'; System.out.println(monkey.name); System.out.println(monkey.level); System.out.println(monkey.gender); monkey.fight("Golden cudgel"); System.out.println("Hahahahahaha"); } }
Classification of variables
Variables are divided into two categories: global variables (attributes) and local variables.
global variable | local variable | |
---|---|---|
position | Out of class method | In the method, the formal parameters of the method |
jurisdiction | Must have permission | No permission |
Default value | There are default values | No default value |
Scope of action | Entire class {} | Where {} |
life cycle | Generated when the object is created, and the object destruction disappears | Statement block {} |
Memory | Heap (object instance, large space) | Stack (temporary variable storage) |
be careful:
- When the global variable and the local variable have the same name, the local variable will overwrite the global variable
- If you want to call the overridden attribute in the method, this. attribute
Array and object combination
1. The attribute of the object is array type
public class Student { public String name; public String tel; public int no; //Three grades public double[] scores ; /** * Return to average score */ public double getAvg() { double sum = 0; for (int i = 0; i < scores.length; i++) { sum += scores[i]; } return sum / scores.length; } public void state(int day) { if(day >= 1 && day <= 5) { System.out.println("Have a good class"); }else if(day == 6) { System.out.println("rest"); }else if(day == 7) { System.out.println("Play games"); }else { System.out.println("Illegal date"); } } public String info() { return "Student [name=" + name + ", tel=" + tel + ", no=" + no + ", scores=" + Arrays.toString(scores) + "]"; } }
Test class:
public class TestStudent { public static void main(String[] args) { Student s = new Student(); s.name = "Shen "; s.no = 110; s.tel = "8888666"; s.scores = new double[] {87,100,69}; double avg = s.getAvg(); System.out.println(s.info()); System.out.println("Average score" + avg); s.state(2); } }
2. The elements of the array are object types
Object array: the elements of the array are objects
Syntax:
class [] Array name = new class[size];
public class Goods { public int no; public String name; public double price; public int counts; }
public class TestGoods { public static void main(String[] args) { //Define an array of products Goods [] goods = new Goods[3]; Scanner sc = new Scanner(System.in); //Dynamic assignment for (int i = 0; i < goods.length; i++) { goods[i] = new Goods(); System.out.println("Please enter the product name"); goods[i].name = sc.next(); System.out.println("Please enter the commodity price"); goods[i].price = sc.nextDouble(); System.out.println("Please enter the product number"); goods[i].no = sc.nextInt(); System.out.println("Please enter commodity inventory"); goods[i].counts = sc.nextInt(); } //Array traversal for (Goods g : goods) { System.out.println(g.name + "," + g.price); } //Get the highest price of goods double max = 0; int index = -1; for (int i = 0; i < goods.length; i++) { if(max < goods[i].price) { max = goods[i].price; index = i; } } System.out.println(goods[index].name); //The console receives a fruit name, and the array looks for the existence of equals() int index = -1; System.out.println("Please enter the name of the fruit you need to find:"); String n = sc.next(); for (int i = 0; i < goods.length; i++) { if(goods[i].name.equals(n)) { index = i; break; } } if(index == -1) { System.out.println("There is no such product"); }else { System.out.println(goods[index].name + "," + goods[index].price); } } }
Method call
Call mode
- Object call. After the class creates an object, it calls through the object
public class Student { public String name; public void study() { System.out.println(name + "Studying hard"); } public static void main(String[] args) { Student s = new Student(); s.name = "Zhang Yu"; //Object call method s.study(); } }
2. Methods in the class call each other
public class Student { public String name; //learning method public void study() { //listen to the music music(); System.out.println(name + "Studying hard"); } //listen to the music public void music() { System.out.println(name + "Listening to music"); } }
be careful:
When method a calls method b, execute b first, and then come back to execute a.
public class Test { public void a() { b(); System.out.println("a"); } public void b() { c(); System.out.println("b"); } public void c() { System.out.println("c"); } public static void main(String[] args) { new Test().a(); // c b a } }
Set return value:
public void a() { b(); System.out.println("a"); } public void b() { System.out.println("b"); System.out.println("2" + c()); } public int c() { System.out.println("c"); return 2; } // b c 22 a
- Recursive call (understand)
Methods call themselves. Recursive calls must have an end condition, otherwise dead recursion and stack overflow will be caused.
public class Num { /** * Factoring * * 1! = 1 * 2! = 1! * 2 * 3! = 2! * 3 * .. * n! = (n - 1)! * n */ public int getJc(int n) { if(n == 1) { return 1; } return getJc(n - 1) * n; } public static void main(String[] args) { Num n = new Num(); int res = n.getJc(3); System.out.println(res); } }
Comprehensive exercise:
public class ScoreCalc{ public int[] scores ; public double sum() { double sum = 0; for (int i = 0; i < scores.length; i++) { sum += scores[i]; } return sum; } public double avg() { return sum() / scores.length; } public void print() { System.out.println("Average score:" + avg()); } } /** test */ public class TestScore { public static void main(String[] args) { ScoreCalc c = new ScoreCalc(); c.scores = new int[] {100,67,74}; c.print(); } }
Number of method parameters
- Method overloading: show the diversity of methods (more than two)
Meet the conditions:
- Same method name
- The parameters of the method must be different: number, type, order
- Arguments automatically call methods corresponding to formal parameters
public class Student { /** * Calculate the sum of two numbers */ public int sum(int a,int b) { return a + b; } /** * Calculate the sum of three numbers */ public int sum(int a,int b,int c) { return a + b + c; } public double sum(double a,double b) { return a + b; } public double sum(double a,int b) { return a + b; } public double sum(int a,double b) { return a + b; } //Same method // public int sum(int c,int d) { // // } //test sum(1,2,3); }
2. Variable length parameter (jdk5+)
When used in the design method, the number of parameters is not limited
Control permission return value method name([Parameter type parameter variable , ] data type...Variable length parameter variable){ Method body; return value; }
be careful:
- Variable length parameters must be placed at the end of the parameter list
- When variable length parameters are defined, the number of arguments passed may not be fixed
- In the method, the variable length parameter is used as an array
public class Student { //Variable length parameter method, p parameter variable public int sum(int ...p) { int sum = 0; for (int i = 0; i < p.length; i++) { sum += p[i]; } return sum; } public static void main(String[] args) { Student s2 = new Student(); //Any number of arguments int res = s2.sum(1,2,3,4,5,10); System.out.println(res); } }
Method call parameter passing
When the method is called, the argument is passed and assigned to the formal parameter
1. Basic data type: values are transferred
2. Reference data type: Address (Reference) is passed
public class Param1 { public static void change(int a,int[]b,Person p) { a = 10; //b = new int[] {2,4,6,8}; b[0] = 88; p.face = "Cry chirp"; } public static void main(String[] args) { int a = 20; int [] b = {1,2,3,4}; Person p = new Person(); p.face = "Giggle"; change(a,b,p); System.out.println(a);// 20 System.out.println(Arrays.toString(b)); //88 2 3 4 System.out.println(p.face); // Cry chirp } }
Stack diagram:
Method transmission case:
public class Param2 { public static void change(int x,int y,Birth b,String s) { //exchange int temp = x; x = y; y = temp; System.out.println(x + "," + y);// 200 100 b = new Birth(); b.date = 30; s = "abc"; } public static void main(String[] args) { int x = 100, y = 200; Birth b = new Birth(); b.year = 2002; b.month = 5; b.date = 9; //The string type parameter transfer is special String a = "123"; change(x,y,b,a); System.out.println(x + "," + y);// 100 200 System.out.println(b.date);//9 System.out.println(a);//123 } } public class Birth { public int year; public int month; public int date; }
Construction method
Also called a constructor, it is a special method in a class. (key)
Function: it can directly assign values to attributes (attribute initialization) when creating objects.
Syntax:
Control permission class name(Parameter type variable, Parameter type variable 2...){ Method body (assign values to attributes) }
be careful:
- No return declaration for method
- The method name of the constructor is the class name
Parameterless constructor:
public Birth() { System.out.println("Created a birthday object"); }
Construction method with parameters:
public Birth(int year,int month,int date) { this.year = year; this.month = month; this.date = date; }
Caller of constructor: JVM automatic call
Call time of construction method: new object
Call times of construction method: 1
Classification of construction methods:
- Default constructor when a constructor is not defined, the system will automatically create a default constructor
public class(){ }
2. When the construction method is manually defined, the default parameterless construction method is overwritten.**Therefore, when you create a construction method, you must add a parameterless construction.** 3. The construction method can realize overloading: it can be realized according to different parameters of the method
Difference between construction method and ordinary method:
Construction method | Common method | |
---|---|---|
Return type | No return declaration | Must declare void |
Call mode | JVM | Object. Method () |
effect | Initialize properties | custom |
Call time point | new when creating an object | custom |
Members in class: attribute + method + constructor
Think: can a common method in a class be a class name as a method name? Yes, not recommended. Declare return value type
Chapter II three basic characteristics of object-oriented
Three basic characteristics of object-oriented: encapsulation, inheritance and polymorphism
1. Encapsulation, information hiding, data packaging, security
2. Inherited code inheritance and code reuse
3. Polymorphism: one parent has multiple subclasses, and the code is highly extensible
Encapsulation
What is encapsulation: hide the information of the members (attributes, methods, construction methods) in the class, privatize the information, and cannot access all places outside the class.
Function of encapsulation: ensure the security of data and ensure that data is not used illegally
How to realize encapsulation?
- The member permissions that need to be encapsulated are changed to private
Control permission: (restrict the scope of use of members)
The whole project exposed by public can be used
Private private current class
be careful:
In enterprise development, in order to ensure data security, all attributes will be privatized.
The encapsulated attribute needs to provide a set of methods setXX() to set the value of the attribute, and getXX() to obtain the value of the attribute
public class Emp { //Privatization attribute private int eno; private String ename; private double sal; //Construction method public Emp() { } public Emp(int eno, String ename, double sal) { super(); this.eno = eno; this.ename = ename; this.sal = sal; } /** * Get the value of eno */ public int getEno() { //Judgment can be added return eno; } /** * How to get paid */ public double getSal() { return sal; } /** * How to set salary */ public void setSal(double sal) { if(sal < 0) { System.out.println("Illegal salary"); }else { this.sal = sal; } } }
Test class:
public class TestEmp { public static void main(String[] args) { Emp p = new Emp(1,"jack",4000); //Get employee number System.out.println(p.getEno()); //Set salary p.setSal(-9); //Get salary //System.out.println(p.getSal()); } }
be careful:
setXX() xx attribute name must have parameters
getXX() xx attribute name must have a return value
What happens after packaging?
The whole process of attribute assignment:
- Default value
- Declared value
- Construction method (the first value when the object is created)
- set() (to modify the attribute value of the object)
Encapsulation of methods (encapsulation of construction methods)
Encapsulation method: when some methods in the class do not want to be called by external classes, they are only used inside the class.
Encapsulation construction method: the class does not want to be created (singleton mode)
public void open() { //Internal retrieval parts startFixes(); System.out.println("TV on"); } //Packaging method private void startFixes() { System.out.println("....Part 1"); System.out.println("....Part 2"); System.out.println("....Part 3"); }
public class Math{ //Packaging construction method private Math(){ } }
Singleton mode:
public class Earth { private static Earth earth = new Earth(); private Earth() { } public static Earth getEarth() { return earth; } }
The composition of a JAVA source file Animal.java
Package declaration (1 time) |
---|
Declaration of guided package (n times) |
Class declaration (n): attribute, method, constructor |
package package; import package; public class Class name{ //attribute //method //structure } class Class name{ //attribute //method //structure }
Package: equivalent to folder in JAVA.
effect:
- Store logically related classes together
- Restrict access to classes
Package declaration:
package Root package.subpackage .subpackage ; package com.qf.oop;
be careful:
1. All package names are in lowercase
2. Between bags Interval, naming: website suffix. Company name Project name website suffix. Company name. Project name.emp
3. The package declaration must be valid in the first line of the source file
Import package declaration:
import Root package.subpackage .*; //Import all resources in the package import java.util.Arrays; //Import classes defined in JAVA import com.qf.homework.Student; //Import custom cross package classes
Note: you can import multiple classes
Package (API) provided in JAVA
java.lang core package system, string, math
java.util toolkit collection, date, arrays, scanner
java.io package read / write file
java.net network
java.awt graphics window
be careful:
Only java Lang does not need to be imported manually; Shortcut key: ctrl + shift + o
Inheritance
Relationship between classes
1. Association (including) "has a
2. Inheritance (generalization) "is a"
3. Use "use a" for "dependent"
Association (including relationship)
//Class A contains the attributes of class B type: //1 to 1 1 to many object array, set) many to many class A{ //One to many private B[] b; //one-on-one private C c; } class B{ } class C{ } For example: Order class: an account class, n Commodity categories
inherit
//Class A meets class B, and class A inherits the code of B public class A extends B{ } For example, cats inherit animals
rely on
//A certain behavior of class a depends on the implementation of class B public class Student{ public void goToSchool(Bike b){ } public void goToSchool(Car c){ } public void goToSchool(Bus b){ } // .. }
Association relationship: Class A includes class B, and class B is the attribute of class A
Example: Zoo tigers; Restaurant dishes; Sports events of the games; Beauty clothing
Library, books; Meituan shop; Supermarket products
Bank customer accounts;
User class:
package com.qf.oop.bank; public class User { private String name; private String card; private String tel; //contain private Account acc; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getCard() { return card; } public void setCard(String card) { this.card = card; } public String getTel() { return tel; } public void setTel(String tel) { this.tel = tel; } public Account getAcc() { return acc; } public void setAcc(Account acc) { this.acc = acc; } @Override public String toString() { return "user [name=" + name + ", card=" + card + ", tel=" + tel + ", acc=" + acc + "]"; } public User(String name, String card, String tel) { super(); this.name = name; this.card = card; this.tel = tel; } public User() { } }
Account type:
package com.qf.oop.bank; public class Account { private int accNo; private String pass; private double balance; public Account(int accNo, String pass, double balance) { super(); this.accNo = accNo; this.pass = pass; this.balance = balance; } public Account() { } public int getAccNo() { return accNo; } public void setAccNo(int accNo) { this.accNo = accNo; } public String getPass() { return pass; } public void setPass(String pass) { this.pass = pass; } public double getBalance() { return balance; } @Override public String toString() { return "Account [accNo=" + accNo + ", pass=" + pass + ", balance=" + balance + "]"; } /** * save money */ public boolean deposit(double mon) { if(mon > 0 && mon % 100 == 0) { balance += mon; return true; }else { return false; } } /** * Withdraw money */ public boolean withdraw(double mon) { if(mon <= balance) { balance -= mon; return true; }else { return false; } } }
Banking:
package com.qf.homework; import java.util.Scanner; public class Banking { public static void main(String[] args) { int[] acc = { 1001, 1002 }; String[] pass = { "123456", "666666" }; double[] balance = { 5000, 1000 }; Scanner sc = new Scanner(System.in); while (true) { System.out.println("Welcome to ATM System: 1.Login 2.Exit the system"); System.out.println("Please enter the operation number:"); int opp = sc.nextInt(); if(opp == 1) { System.out.println("Please enter your account name:"); int no = sc.nextInt(); // Find account int index = -1; for (int i = 0; i < acc.length; i++) { if (acc[i] == no) { index = i; break; } } if (index != -1) { System.out.println("Please enter your password:"); String password = sc.next(); if (pass[index].equals(password)) { // Correct password System.out.println("Login successful"); while (true) { System.out.println("1.save money"); System.out.println("2.Withdraw money"); System.out.println("3.View balance"); System.out.println("4.transfer accounts"); System.out.println("5.sign out"); System.out.println("Please enter the operation number"); int opr = sc.nextInt(); if (opr == 1) { System.out.println("Please enter the deposit amount"); // Whole hundred > 0 double money = sc.nextDouble(); if (money % 100 == 0 && money > 0) { balance[index] += money; } else { System.out.println("Incorrect amount"); } } else if (opr == 2) { System.out.println("Please enter the withdrawal amount"); // judge double money = sc.nextDouble(); if (money > 0 && money <= balance[index]) { balance[index] -= money; } else { System.out.println("Sorry, your credit is running low"); } } else if (opr == 3) { System.out.println("Current balance:" + balance[index]); } else if (opr == 4) { System.out.println("Please enter the transfer account"); int no2 = sc.nextInt(); int index2 = -1; for (int i = 0; i < acc.length; i++) { if (acc[i] == no2) { index2 = i; break; } } if (index2 != -1) { System.out.println("Please enter the transfer amount"); double m = sc.nextDouble(); if (m <= balance[index]) { // index2 account+ balance[index2] += m; // index - balance[index] -= m; System.out.println("Transfer succeeded"); } else { System.out.println("Insufficient amount"); } } else { System.out.println("Without this account, transfer cannot be made"); } } else if (opr == 5) { break; } else { System.out.println("Operation error"); } } } else { System.out.println("Password error"); } } else { System.out.println("No such account"); } } else if(opp == 2){ System.exit(0); }else { System.out.println("Operation error"); } } } }
Test class:
package com.qf.oop.bank; public class TestBank { public static void main(String[] args) { new Bank(); } }
What is inheritance?
The process of using existing classes to build new classes, code inheritance.
Existing classes: parent class, root class, superclass, base class
Build a new class: subclass, derived class, derived class
"Yes", is a, such as tigers (subclasses meet the characteristics of the parent class, the subclasses are relatively specific, and the parent class is relatively abstract); Shoes and clothing; Primary school students
The role of inheritance: code reuse to avoid code redundancy
How to implement inheritance?
Control authority class Subclass extends Parent class{ }
be careful:
Control permission: public or no permission default
Only one parent class can inherit from a subclass
Parent class:
public class Emp extends Object{ private int eNo; private String eName; private double eSal; public int geteNo() { return eNo; } public void seteNo(int eNo) { this.eNo = eNo; } public String geteName() { return eName; } public void seteName(String eName) { this.eName = eName; } public double geteSal() { return eSal; } public void seteSal(double eSal) { this.eSal = eSal; } public Emp(int eNo, String eName, double eSal) { super(); this.eNo = eNo; this.eName = eName; this.eSal = eSal; } public Emp() { } @Override public String toString() { return "Emp [eNo=" + eNo + ", eName=" + eName + ", eSal=" + eSal + "]"; } }
Subclass:
public class Manager extends Emp{ //bonus private double bonus; public double getBonus() { return bonus; } public void setBonus(double bonus) { this.bonus = bonus; } @Override public String toString() { //super.toString() of parent class return super.toString() + "Manager [bonus=" + bonus + "]"; } }
Test class:
Manager m = new Manager(); m.seteNo(2); m.seteName("rose"); m.seteSal(6000); m.setBonus(30000); System.out.println(m);
What can be inherited?
Inheritable: non private properties and methods
No: private, and the constructor cannot inherit
Therefore: in subclasses: members of the parent class + members of the subclass itself
Problems after inheritance
1. Inheritance relationship in Java? There is only single inheritance between classes (a parent class can have multiple subclasses, and each subclass can only have one parent class)
2. The inheritance relationship in Java is multi-layered. The higher the upper level is, the more abstract it is, and the lower the level is, the more specific it is
3. Object is the ancestor class of all classes, top-level, and all classes inherit this class directly or indirectly.
4. Permissions in Java (key)
public | protected | default | private | |
---|---|---|---|---|
meaning | Public | Protected | Friendly, default | Private |
Range | Entire project | Same package access, cross package inheritance | Same package access | Current class |
Range sorting: public > protected > Default > private
public class A { public int a = 10; protected int b = 20; int c = 30; private int d = 40; }
use:
Class, interface: public, default
Attributes: Four
Method, construction: Four
Local variable: no permission
Method overloading and overriding (overriding)
When multiple methods have the same method name, they need to be overloaded or overridden if they want to coexist.
Overloading of methods: (diversification of methods) overload
principle:
1. Same method name
2. Parameters must be different (number, order, type)
3. Permissions and return values do not affect
Override of methods: (override of methods, subclasses transform the methods inherited by the parent class) override
principle:
1. Same method name
2. The parameters must be the same
3. The return value must be the same
4. Permission cannot be reduced public > protected > Default > private
package com.qf.oop; public class Father { /** * heavy load * @param t */ public void eat() { System.out.println("Dad eats meat"); } public void eat(String t) { System.out.println(); } public int eat(String t,double k) { return 0; } } class Son extends Father{ /** * rewrite */ public void eat() { System.out.println("Children drink milk"); } } public class TestFather { public static void main(String[] args) { Father f = new Father(); //Dad eats meat f.eat(); Son s = new Son(); //Call the method after rewriting //Children drink milk s.eat(); s.eat("Wow haha"); } }
Summarize the difference between overloading and Rewriting:
heavy load | Rewrite (overwrite) | |
---|---|---|
overload | override | |
objective | Diversification of methods | Subclass overrides parent |
parameter | Parameters must be different | Parameters must be the same |
jurisdiction | Unlimited | Subclasses cannot reduce permissions |
Return value | Unlimited | Must be the same |
position | This class, parent-child class | Parent child class |
frequency | n times | Once |
abnormal | Unlimited | Subclasses cannot throw more exceptions |
Construction method in inheritance (difficulty)
- Subclasses cannot inherit the constructor of the parent class
- The subclass needs to manually call the constructor of the parent class:
public Subclass(Type parameter variable ){ //Properties inherited by parent class super(Argument 1,Argument 2); //Self defined attributes this.xx = xx; }
The subclass manually calls the constructor of the parent class:
public Manager(int eNo, String eName, double eSal,double bonus) { //Call parent class super(eNo,eName,eSal); //own this.bonus = bonus; } //call public Emp(int eNo, String eName, double eSal) { super(); this.eNo = eNo; this.eName = eName; this.eSal = eSal; } //Instantiation: public class TestEmp { public static void main(String[] args) { //Emp e = new Emp(1, "jack", 4000); //System.out.println(e); Manager m = new Manager(2, "rose", 6000, 30000); // m.seteNo(2); // m.seteName("rose"); // m.seteSal(6000); // m.setBonus(30000); System.out.println(m); } }
- In inheritance, the execution order of construction methods is: ancestor > parent > child
- When there is no super (parameter) in the first line of the construction method, the system provides super() by default; The default construction of the parent class is automatically called, so the empty construction is guaranteed
public class GrandPa { public GrandPa() { super(); System.out.println("Grandpa is here"); } } public class Father extends GrandPa{ public String name; public Father(String name) { //super() System.out.println("Here comes dad"); } // public Father() { // // } } public class Son extends Father{ public Son(String name) { //super() super(name); System.out.println("Here comes the child"); } } public class TestSon { public static void main(String[] args) { Son son = new Son("jack"); } }
Summarize the use of super and this
Usage of super
- Call the overridden properties and methods of the parent class in the subclass
public class Student extends Person{ public String name = "Xiao Wang"; @Override public String toString() { return "father:" + super.name + ";children:" + this.name; } }
public class Student extends Person{ public String toy; @Override public String toString() { return super.toString() + "toy=" + toy; } }
- Call the constructor of the parent class
public Person(String name) { this.name = name; } public Person() { //super(); // default }
public Student() { //super();// Empty construct of parent class } public Student(String name) { super(name); // Manual call }
Note: super() calls the constructor, which must be placed in the first line of the constructor.
Usage of this: (current object, object itself)
- Call the properties and methods of this class (especially the global variables are overwritten by local variables)
public void setToy(String toy) { this.toy = toy; }
- Call the constructor of this class
public Emp(int empno, String ename, double sal, int deptno) { this(empno,deptno); //Call the following constructor this.ename = ename; this.sal = sal; } public Emp(int empno, int deptno) { super(); this.empno = empno; this.deptno = deptno; }
Note: this() calls the constructor, which must be placed on the first line of the constructor.
Polymorphism
What is polymorphism?
A parent class presents multiple subclass forms, and the same action shows different behaviors.
True polymorphism:
Parent polymorphic object = new Subclass(); // Upward transformation
Parent: Animal
Subclass: Tiger Rabbit Cat Dog Pig
Animal a = new Animal() Tiger t = new Tiger(); Cat c = new Cat(); Dog d = new Dog();
Flexible polymorphism:
Animal a = new Dog();
Examples of polymorphism in life: USB: fan, keyboard, mouse, humidifier
USB b = new Mouse(); USB b = new KeyBoard();
The benefits of polymorphism?
Make the code more flexible and extensible
In depth analysis of polymorphism
Animal a = new Dog();
Angle 1: type conversion (compilation angle)
When there is an inheritance relationship:
Parent object name = new Subclass(); // Automatic transformation upward transformation Subclass object name = (Subclass)new Parent class(); // Forced transformation downward transformation
Angle 2: operation of polymorphic bottom layer
Access to polymorphic objects
Only members of the parent class can be accessed, and the methods of the child class are executed if and only if the child class overrides the methods of the parent class.
Necessary conditions for polymorphic design
1.Inheritance. A parent class has multiple subclasses 2.Subclasses must override the methods of the parent class 3.Object upward transformation
Parent class:
public class USB { private String name; public USB() { } public USB(String name) { super(); this.name = name; } public String getName() { return name; } public void setName(String name) { this.name = name; } public void use() { System.out.println("usb work...."); } }
Subclass:
public class Mouse extends USB{ @Override public void use() { System.out.println(getName() + "usb Mouse work...."); } public Mouse() { super(); // TODO Auto-generated constructor stub } public Mouse(String name) { super(name); // TODO Auto-generated constructor stub } } public class KeyBoard extends USB{ @Override public void use() { System.out.println(getName() + "usb Keyboard operation...."); } public KeyBoard() { super(); // TODO Auto-generated constructor stub } public KeyBoard(String name) { super(name); // TODO Auto-generated constructor stub } }
Test class:
public class TestUSB { public static void main(String[] args) { //USB u = new Mouse("Logitech"); USB u = new KeyBoard("Cherry"); u.use(); } }
Practical application of polymorphism
Parameters of dependencies
public class Developer { /** * Dependency * @param u */ public void useTool(USB u) { //Call overridden method u.use(); } }
Developer testing tools:
public class TestUSB { public static void main(String[] args) { Developer d = new Developer(); d.useTool(new KeyBoard("Cherry"));//USB u = new KeyBoard("cherry"); } }
Note: construction methods cannot be overridden and can be overloaded
instanceof downward transformation
Used to determine the specific type of an object: (see new)
object instanceof Type (class/Interface)
1. Boolean type is returned: true (object is type; object is subclass type of type); false (not this type)
2. If there is no connection between the object and the type, a compilation error occurs
Cat c = new Cat(); Animal a = new Animal(); Animal a2 = new Tiger();//Transform polymorphic objects upwards System.out.println(c instanceof Cat); // true object is cat type System.out.println(c instanceof Animal); // The true object is a cat, and the type is an Animal subclass System.out.println(a instanceof Animal); //System.out.println(c instanceof Student); //System.out.println(c instanceof Tiger);// Tiger Cat has no contact, no brotherhood System.out.println(a instanceof Cat); // false the animal object is not necessarily a cat System.out.println(a instanceof Object);//true System.out.println(c instanceof Object);//true System.out.println(a2 instanceof Cat);//Judge whether it is a cat
The purpose is to transform polymorphic objects downward and obtain resources in subclasses:
Animal a = new Cat(); a.eat(); if(a instanceof Tiger) { Tiger t = (Tiger)a;//Downward transformation t.ao(); }
Chapter 3 advanced object-oriented features
abstract
What is abstract?
Abstract, difficult to describe clearly, relatively general. The concept is vague.
What can abstract modify?
1. Class abstract class (Abstract parent class)
public abstract class Class name{ }
2. Method abstract method
Control authority abstract Return type method name(Parameter type variable ,Parameter type variable 2 ) ;
Characteristics of abstract classes
1. Abstract classes are generally used as parent classes, and abstract classes cannot be instantiated
2. Abstract parent class requires that there must be subclass inheritance, and subclasses describe it clearly (there must be subclass inheritance)
3. After the subclass inherits the abstract parent class, it must override all the abstract methods * * * *, otherwise the class will become an abstract class****
4. Abstract classes are not necessarily abstract methods, and there can be non abstract methods; Classes with abstract methods must be abstract classes
5. Does the abstract class contain construction methods?
Abstract parent class:
public abstract class Fly { private String name; /** * Abstract method */ public abstract void fly(); // public abstract void hua(); /** * Non Abstract * @return */ public String getName() { return name; } }
Subclass inheritance and override:
public class Bird extends Fly{ @Override public void fly() { System.out.println("Bird flight"); } } public class Plane extends Fly { @Override public void fly() { System.out.println("Aircraft flight"); } }
Test class:
public class TestFly { public static void main(String[] args) { //Abstract classes cannot instantiate objects //Fly f = new Fly(); //Upward transformation Fly f = new Plane(); f.fly(); } }
Note: Abstract parent classes have construction methods that are called for subclasses.
Characteristics of abstract methods
1. The behavior that cannot be described must not have a method body and cannot add {}
2. Classes containing abstract methods must be abstract classes
public abstract void fly();
static
What is static?
Static, belonging to a class, and no longer belonging to an object.
What can static modify?
Attribute, method, inner class
public class Test { //Static attribute, class attribute private static int a ; /** * Static method, class method * @param args */ public static void test() { //Local variables cannot be static int b = 10; } }
Static attribute?
Add static attributes: static attributes, class attributes, are resources shared by all objects, and no longer belong to an object alone. For example: sharing cars and private cars; Internet cafe computer, own computer;
Attribute not added: instance attribute, which is a unique resource of each object.
Person: name, age, subject (primate), skin color
public class Person { //Instance properties private String name; private int age; //Static properties private static String type = "Primates"; }
Features of detecting static attributes:
package com.qf.oop; public class TestStatic { public int i = 10; public static int j = 20; public TestStatic() { i ++; j ++; } public static void main(String[] args) { TestStatic t1 = new TestStatic(); System.out.println(t1.i + "," + t1.j);// 11 21 TestStatic t2 = new TestStatic(); System.out.println(t2.i + "," + t2.j);// 11 22 } }
Stack diagram:
The difference between static attributes and instance attributes: (remember)
Static properties | Instance properties | |
---|---|---|
meaning | Objects belonging to classes share resources | Unique to each object |
number | One copy of a class | n copies |
memory allocation | Static area | heap |
Initialization timing | When the class is loaded (before the class is used) | create object |
call | Class Static attribute / object. Static attribute | Object. Instance properties |
Call:
public class TestStatic { public int i = 10; //Instance properties public static int j = 20; //Static properties public TestStatic() { i ++; j ++; } public static void main(String[] args) { TestStatic t = new TestStatic(); // B error. The rest are right // A t.i // B TestStatic.i // C TestStatic.j // D t.j } }
Static method?
- Static methods can only call static properties and methods, not non static properties and methods
- Instance methods can call static methods
- When a static method is to call non static: only objects can be created
- Class name Static method () recommended / object Static method () yes
package com.qf.oop; /** * Test the invocation of static methods * @author 86136 * */ public class Test2 { int a = 10; static int b = 10; public static void main(String[] args) { System.out.println(Math.random()); t1(); //Non static methods can only be used after creating objects Test2 ttt = new Test2(); ttt.t3(); } //Static method public static void t1() { System.out.println(b); Test2 ttt = new Test2(); System.out.println(ttt.a); t2(); //t3(); } public static void t2() { } //Instance method public void t3() { System.out.println(a); System.out.println(b); t1(); t2(); } }
Static code block?
Static code blocks are used to initialize static members.
//Static code block static{ // Initialize static properties } //Instance code block { }
1. The location and construction method are at the same level
2. There can be multiple numbers, which are executed in sequence
3. When the opportunity class is loaded
4. Times 1 time
5. Sequence static1 > instance n > construct n
public class Test3 { public static int a ; public int b; static { //a = 20; System.out.println("Static code block"); } // static { // a = 30; // } { System.out.println("Instance code block"); } public Test3(int b) { System.out.println("Construction method"); this.b = b; } }
final
What is final: final, final.
What final modifies: variable (attribute + local variable) constant
method
class
public final class TestFinal { public final String TEACHER = "Miss Yu"; public final void test() { final int YEAR = 365; } }
What are the characteristics of final decoration content?
1. final Modified variable: constant, which cannot be modified once defined; final The decorated attribute must be set to the initial value, and the default value cannot be used 2. final Modification method: cannot be rewritten 3. final Decorated class: cannot have subclasses (the last class) JAVA Which classes in final Decoration class: Math ,String,Integer
Modifier sharing
abstract: class method
static: attribute method
final: variable method class
1. It cannot be mixed
abstract and static
abstract and final
abstract and private
2. It can be mixed
static and final can modify attributes and methods together, without limiting the order
public class TestFinal2 { public final static int AGE = 20; public static final double PI = 3.14159265358979323846; public static void main(String[] args) { System.out.println(TestFinal2.AGE); System.out.println(TestFinal2.PI); } public static final void test() { } }
Chapter IV interface
Significance of interface
When a subclass inherits the parent class, it cannot have the characteristics of other parent classes. The interface can make the class have a variety of characteristics.
The purpose is to solve the problem of single inheritance.
As a reference data type, interface abstracts the concept and only defines method declarations. what is ? (definition) How is? (no matter what)
Note: in development, design and implementation are separated, and the interface is the design level. What is the architect's design; Class is the implementation level, which implements the content defined in the interface
Definition of interface
Control authority interface Interface name{ }
be careful:
1. Control permission public default
2. Keyword interface
3. Interface name: similar name, iweapon, ivehicles
Implementation of interface
Control authority class Implementation class extends Parent class implements Interface 1,Interface 2...{ }
be careful:
Implementation classes can implement multiple interfaces at the same time, with a variety of characteristics
Inheritance can only have one parent class and implement multiple interfaces (single inheritance, multiple implementation)
Case:
//Weapon interface public interface IWeapon { } //Vehicle interface public interface IVehicles { } //Steel parent public abstract class Iron { } //Implementation class public class Tank extends Iron implements IWeapon,IVehicles{ } //Abstract class implementation public abstract class UFO implements IWeapon, IVehicles{ }
Note: XXXImpl
Members in the interface
Attributes: exposed static constants public static final = Initial value; Methods: open abstract methods public abstract Return value method name(parameter) ;
be careful:
- The modifiers of attributes and methods in the interface are all fixed by default. Even if omitted, they must be of this type
- There is no constructor in the interface, so it must not be instantiated
public interface IWeapon { //static const public static final int POWER = 100; int DEFENCE = 50; //Abstract method public abstract void fire() ; String fix(int hour); }
Implementation of implementation class
1. Cover all abstract methods in the interface
public class Gun implements IWeapon{ @Override public void fire() { System.out.println("Fire"); } @Override public String fix(int hour) { System.out.println("maintain" + hour + "hour"); return "Recovery, ready"; } }
2. Constants in the interface
Interface name. Attribute, used directly and cannot be modified
3. Polymorphism in the interface
Interface type polymorphic object = new Implementation class();
public interface Photograph { void shot(); } class Camera implements Photograph{ @Override public void shot() { System.out.println("Camera photography"); } } class Phone implements Photograph{ @Override public void shot() { System.out.println("Take photos with mobile phone"); } }
public class Photographer { private static final String NAME = "people with a deep sense of justice"; /** * Take photos with equipment */ public void takePhoto(Photograph p) { System.out.println(NAME + "photograph:"); p.shot(); } /** * test */ public static void main(String[] args) { new Photographer().takePhoto(new Camera()); } }
relationship | Inheritance angle | keyword | ||
---|---|---|---|---|
Classes and classes | Single inheritance | A parent class has multiple subclasses, and each subclass has a parent class | extends | public class subclass extends parent class {} |
Classes and interfaces | Multiple implementations | Interface has multiple implementation classes, and each implementation class implements multiple interfaces | implements | public class implements class implements interface 1, interface 2... {} |
Interfaces and interfaces | Multiple inheritance | The parent interface can have multiple sub interfaces, and each sub interface inherits multiple parent interfaces | extends | public interface sub interface extends parent interface 1, parent interface 2... {} |
public interface A extends B,C{ } interface B { } interface C { }
Differences between abstract classes and interfaces (emphasis)
abstract class | Interface | |
---|---|---|
definition | abstract class | interface |
attribute | Customize private | public static final |
method | Custom (Abstract + non Abstract) | public abstract |
Construction method | have | nothing |
Relationship with class | Single inheritance | Multiple implementations |
Similarities: 1. There are abstract methods. 2. Objects cannot be instantiated, and new is not allowed
Special case: jdk8+
public interface More { public abstract void test(); /** * jdk8+ Non abstract method */ public default void test2() { } }
Chapter V enumeration
The meaning of enumeration
Enumeration means to enumerate one by one, which is used for a set of fixed discrete values, such as male and female with fixed gender; Month 1-12; Four seasons, week, twelve zodiac signs, four famous works, RMB face value (100, 50, 20, 10, 5, 1), traffic lights (red, green, yellow), 26 letters.
The role of enumeration
- The code is more secure and will not be called illegally
- Reduce code coupling
- The readability of the code is enhanced. int and String are not used to represent its meaning
Declaration of enumeration
Control authority enum Enum name{ }
be careful:
Control permission: public default
Enumeration name: capitalized, legal identifier
Members in enumeration
Control authority enum Enum name{ enumeration constant , Enumeration constant 2 ; }
Member calls in enumeration
Enum name.enumeration constant
public enum Light { RED,GREEN,YELLOW; } public class TestLight { public static void main(String[] args) { System.out.println(Light.RED); } }
Use enumeration in switch:
/** * traffic * @author 86136 * */ public class Traffic { //Define the attribute and switch the color of the signal lamp private Light curr ; public Light getCurr() { return curr; } public void setCurr(Light curr) { this.curr = curr; } /** * Signal switching */ public Light change(Light l) { switch (l) { case RED: curr = Light.GREEN; break; case YELLOW: curr = Light.RED; break; case GREEN: curr = Light.YELLOW; break; } return curr; } } /*test*/ public class TestTraffic { public static void main(String[] args) { Traffic t = new Traffic(); //switch System.out.println(t.change(Light.RED)); } }
Factory model
23 design modes: Singleton mode, static factory mode, agent mode, producer consumer
Singleton mode: only one object instance can be obtained
public class Singleton{ private static Singleton ins = new Singleton(); /** Use method to return an instance*/ public static Singleton getSingleton(){ return ins; } }
Case:
public class Earth { private static Earth ins = new Earth(); private Earth() { } /**Use method to return an instance*/ public static Earth getEarth(){ return ins; } } public class TestEarth { public static void main(String[] args) { Earth e1 = Earth.getEarth(); Earth e2 = Earth.getEarth(); System.out.println(e1 == e2);//Single instance } }
Static factory mode: produce objects according to type needs.
public interface IShoe { public abstract void info(); } public enum ShoesType { ADIDAS,NIKE,ANTA; } public class Nike implements IShoe{ @Override public void info() { System.out.println("Nike shoes are light and easy to wear"); } } public class Adidas implements IShoe{ @Override public void info() { System.out.println("Adidas is good-looking and resistant to manufacturing"); } } public class Anta implements IShoe{ @Override public void info() { System.out.println("Anta never stops"); } } /** * Static factory * @author 86136 * */ public class ShoesFactory { private static IShoe shoe; /** * Polymorphic attribute * @param type * @return */ public static IShoe make (ShoesType type) { switch (type) { case ADIDAS: shoe = new Adidas(); break; case NIKE: shoe = new Nike(); break; case ANTA: shoe = new Anta(); break; } return shoe; } } public class TestFactory { public static void main(String[] args) { //polymorphic IShoe shoe = ShoesFactory.make(ShoesType.NIKE); shoe.info(); } }
Chapter VI internal classes
What is an internal class?
The classes defined in a class are called internal classes, and the external classes are called external classes.
Classification of internal classes
① Static inner class
② Instance inner class
③ Local inner class
public class Outer { /** * Static inner class * */ public static class Inner{ public int a = 10; public static int b = 20; } /** * Instance inner class * */ public class Inner2{ public int a = 30; } public void test() { //Local inner class class Inner3{ } } }
Static inner class:
External class.Static inner class
public class TestInner1 { public static void main(String[] args) { Outer.Inner inner = new Outer.Inner(); System.out.println(inner.a); System.out.println(Outer.Inner.b); } }
Instance inner class:
new External class().new Instance inner class();
public class TestInner2 { public static void main(String[] args) { Outer.Inner2 inner2 = new Outer().new Inner2(); System.out.println(inner2.a); } }
Local internal classes: look at methods, and external classes call methods
public void test() { //Local inner class class Inner3{ int a = 50; public void test2() { System.out.println("Local inner class"); } } Inner3 inner3 = new Inner3(); System.out.println(inner3.a); inner3.test2(); } public class TestInner3 { public static void main(String[] args) { Outer outer = new Outer(); outer.test(); } }
Anonymous inner class (key)
① This inner class has no name
② The above three inner classes can be anonymous, mainly local inner classes
Abstract parent variable name = new Abstract parent class(){ //Class body of the subclass of the abstract parent class } Interface variable name = new Interface(){ //Class body of implementation class }
public interface IAnimal { void eat(); }
IAnimal animal = new IAnimal() { @Override public void eat() { System.out.println("Kittens eat mice"); } }; animal.eat(); //lambda JDK8+ IAnimal animal2 = () -> System.out.println("Deer eat grass"); animal2.eat();