1. Succession
1.1 implementation of inheritance (Master)
-
Concept of inheritance
- Inheritance is one of the three characteristics of object-oriented. It can make subclasses have the properties and methods of the parent class, redefine them in subclasses, and append properties and methods
-
Implement inherited formats
- Inheritance is implemented through extensions
- Format: class subclass extends parent class {}
- Example: class dog extensions animal {}
-
Benefits of inheritance
- Inheritance can create a relationship between classes and a child parent relationship. After a child parent class is generated, the child class can use the non private members of the parent class.
-
Sample code
public class Fu { public void show() { System.out.println("show Method called"); } } public class Zi extends Fu { public void method() { System.out.println("method Method called"); } } public class Demo { public static void main(String[] args) { //Create an object and call a method Fu f = new Fu(); f.show(); Zi z = new Zi(); z.method(); z.show(); } }
1.2 advantages and disadvantages of inheritance (understanding)
- Inherited benefits
- It improves the reusability of code (the same members of multiple classes can be placed in the same class)
- The maintainability of the code is improved (if the method code needs to be modified, just modify one place)
- Inheritance malpractice
- Inheritance creates a relationship between classes and enhances the coupling of classes. When the parent class changes, the implementation of subclasses has to change, weakening the independence of subclasses
- Inherited application scenarios:
- When using inheritance, you need to consider whether there is an is... a relationship between classes. Inheritance cannot be used blindly
- The relationship between is... A: who is who. For example, teachers and students are a kind of people, that person is the parent, and students and teachers are the children
- When using inheritance, you need to consider whether there is an is... a relationship between classes. Inheritance cannot be used blindly
1.3. Characteristics of inheritance in Java (Master)
-
Characteristics of inheritance in Java
- Classes in Java only support single inheritance, not multiple inheritance
- Error example: class A extends B, C {}
- Classes in Java support multi-layer inheritance
- Classes in Java only support single inheritance, not multiple inheritance
-
Multi level inheritance example code:
public class Granddad { public void drink() { System.out.println("Grandpa likes drinking"); } } public class Father extends Granddad { public void smoke() { System.out.println("Dad likes smoking"); } } public class Mother { public void dance() { System.out.println("Mother loves dancing"); } } public class Son extends Father { // At this point, the Son class has both the drink method and the smoke method }
2. Member access characteristics in inheritance
2.1 access characteristics of variables in inheritance (Master)
Accessing a variable in a subclass method adopts the proximity principle.
- Subclass local range finding
- Subclass member range not found
- Parent class member range not found
- If there is nothing wrong, report an error (regardless of the father's father...)
-
Sample code
class Fu { int num = 10; } class Zi { int num = 20; public void show(){ int num = 30; System.out.println(num); } } public class Demo1 { public static void main(String[] args) { Zi z = new Zi(); z.show(); // Output the local variable 30 in the show method } }
2.2 super
- This & Super keyword:
- This: represents the reference of this class object
- super: represents the identification of the storage space of the parent class (which can be understood as the reference of the parent class object)
- this and super are used respectively
- Member variables:
- This. Member variable - access the member variable of this class
- super. Member variables - access parent member variables
- Member method:
- This. Member method - access the member method of this class
- super. Member method - access parent class member method
- Member variables:
- Construction method:
- this(...) - access the constructor of this class
- super(...) - access the parent class constructor
2.3 access characteristics of construction methods in inheritance (understanding)
Note: all constructors in the subclass will access the parameterless constructors in the parent class by default
Subclasses inherit the data from the parent class and may also use the data from the parent class. Therefore, the parent class data must be initialized before subclass initialization. The reason is that the first statement of each subclass construction method is: super() by default
Question: what if there are no parameterless constructors in the parent class, but only parameterless constructors?
1. through the use of super Keyword to call the parameterized constructor of the parent class 2. Subclass pass this To call other constructor methods of this class,Other construction methods of this class can be passed super Manually call the constructor with parameters of the parent class be careful: this(...)super(...) A valid statement must be placed on the first line of the constructor, and the two cannot coexist
2.4 access characteristics of member methods in inheritance (Master)
Accessing a method through a subclass object
- Subclass member range not found
- Parent class member range not found
- If there is nothing wrong, report an error (regardless of the father's father...)
2.5 super memory diagram (understanding)
-
Object in heap memory, there will be a separate super area to store the data of the parent class
2.6 method rewriting (Mastering)
- 1. Method rewrite concept
- Subclass as like as two peas in the parent class, the same method declaration (the same as the method name, the parameter list must be the same).
- 2. Application scenario of method rewriting
- When a subclass needs the function of the parent class and the subclass of the function subject has its own unique content, you can override the methods in the parent class. In this way, you not only follow the function of the parent class, but also define the unique content of the subclass
- 3. Override annotation
- It is used to check whether the current method is a rewritten method and plays the role of verification
2.7 precautions for method rewriting (Master)
- Method override considerations
- Private methods cannot be overridden (private member subclasses of the parent class cannot inherit)
- Subclass method access permission cannot be lower (public > Default > private)
- Static methods cannot be overridden if the subclass also has the same method, which is not the method of the overridden parent class
- Sample code
public class Fu { private void show() { System.out.println("Fu in show()Method called"); } void method() { System.out.println("Fu in method()Method called"); } } public class Zi extends Fu { /* Compile [error], the subclass cannot override the private method of the parent class*/ @Override private void show() { System.out.println("Zi in show()Method called"); } /* Compile [error]. When the subclass overrides the parent method, the access permission must be greater than or equal to the parent */ @Override private void method() { System.out.println("Zi in method()Method called"); } /* Compile [pass]. When the subclass overrides the parent method, the access permission must be greater than or equal to that of the parent */ @Override public void method() { System.out.println("Zi in method()Method called"); } }
2.8 permission modifier (understood)
2.9 information management system use inheritance and improvement (Master)
-
demand
Extract the common contents of the student class and the teacher class up to a Person parent class, and let the student class and the teacher class inherit the Person class
-
Implementation steps
-
Extract Person class
-
Optimize the inputStudentInfo method in the StudentController class, and improve the setXxx assignment method to construct method initialization
Note: directly modifying this operation mode does not conform to a principle in our development
Open close principle (open to extension and close to modification): try to complete the requirements without changing the original code
Solution: recreate an OtherStudentController class
Write a new inputStudentInfo method
-
Extract the BaseStudentController class from the StudentController class and OtherStudentController class
Let the StudentController class and OtherStudentController class inherit the BaseStudentController class
-
-
code implementation
Person class, student class and teacher class
public class Person { private String id; private String name; private String age; private String birthday; public Person() { } public Person(String id, String name, String age, String birthday) { this.id = id; this.name = name; this.age = age; this.birthday = birthday; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getAge() { return age; } public void setAge(String age) { this.age = age; } public String getBirthday() { return birthday; } public void setBirthday(String birthday) { this.birthday = birthday; } } // Student class public class Student extends Person { public Student() { } public Student(String id, String name, String age, String birthday) { super(id, name, age, birthday); } } // Teacher class public class Teacher extends Person { public Teacher() { } public Teacher(String id, String name, String age, String birthday) { super(id, name, age, birthday); } }
BaseStudentController class
public abstract class BaseStudentController { // Operator object private StudentService studentService = new StudentService(); private Scanner sc = new Scanner(System.in); // Open the student management system and display the student management system menu public void start() { //Scanner sc = new Scanner(System.in); studentLoop: while (true) { System.out.println("--------Welcome to <student> management system--------"); System.out.println("Please enter your choice: 1.Add student 2.Delete student 3.Modify student 4.View student 5.sign out"); String choice = sc.next(); switch (choice) { case "1": // System.out.println("add"); addStudent(); break; case "2": // System.out.println("delete"); deleteStudentById(); break; case "3": // System.out.println("modification"); updateStudent(); break; case "4": // System.out.println("query"); findAllStudent(); break; case "5": System.out.println("Thank you for using the student management system, bye!"); break studentLoop; default: System.out.println("Your input is incorrect, Please re-enter"); break; } } } // Modify student methods public void updateStudent() { String updateId = inputStudentId(); Student newStu = inputStudentInfo(updateId); studentService.updateStudent(updateId, newStu); System.out.println("Modified successfully!"); } // Delete student method public void deleteStudentById() { String delId = inputStudentId(); // 3. Call the deleteStudentById in the operator to delete the student according to the id studentService.deleteStudentById(delId); // 4. Prompt deletion succeeded System.out.println("Delete succeeded!"); } // View student methods public void findAllStudent() { // 1. Call the acquisition method in the salesman to get the student's object array Student[] stus = studentService.findAllStudent(); // 2. Judge whether the memory address of the array is null if (stus == null) { System.out.println("No information found, Please add and try again"); return; } // 3. Traverse the array, obtain student information and print it on the console System.out.println("Student number\t\t full name\t Age\t birthday"); for (int i = 0; i < stus.length; i++) { Student stu = stus[i]; if (stu != null) { System.out.println(stu.getId() + "\t" + stu.getName() + "\t" + stu.getAge() + "\t\t" + stu.getBirthday()); } } } // Add student method public void addStudent() { // StudentService studentService = new StudentService(); // 1. The keyboard receives student information String id; while (true) { System.out.println("Please enter student id:"); id = sc.next(); boolean flag = studentService.isExists(id); if (flag) { System.out.println("Student ID is occupied, Please re-enter"); } else { break; } } Student stu = inputStudentInfo(id); // 3. Pass the student object to the addStudent method in studentservice boolean result = studentService.addStudent(stu); // 4. Print success \ failure on the console according to the returned boolean type result if (result) { System.out.println("Added successfully"); } else { System.out.println("Add failed"); } } // Enter the student id on the keyboard public String inputStudentId() { String id; while (true) { System.out.println("Please enter student id:"); id = sc.next(); boolean exists = studentService.isExists(id); if (!exists) { System.out.println("You entered id non-existent, Please re-enter:"); } else { break; } } return id; } // Enter student information with keyboard // Opening and closing principle: open to extended content and close to modified content public Student inputStudentInfo(String id){ return null; } }
StudentController class
public class StudentController extends BaseStudentController { private Scanner sc = new Scanner(System.in); // Enter student information with keyboard // Opening and closing principle: open to extended content and close to modified content @Override public Student inputStudentInfo(String id) { System.out.println("Please enter student name:"); String name = sc.next(); System.out.println("Please enter student age:"); String age = sc.next(); System.out.println("Please enter student birthday:"); String birthday = sc.next(); Student stu = new Student(); stu.setId(id); stu.setName(name); stu.setAge(age); stu.setBirthday(birthday); return stu; } }
OtherStudentController class
public class OtherStudentController extends BaseStudentController { private Scanner sc = new Scanner(System.in); // Enter student information with keyboard // Opening and closing principle: open to extended content and close to modified content @Override public Student inputStudentInfo(String id) { System.out.println("Please enter student name:"); String name = sc.next(); System.out.println("Please enter student age:"); String age = sc.next(); System.out.println("Please enter student birthday:"); String birthday = sc.next(); Student stu = new Student(id,name,age,birthday); return stu; } }
3. Abstract class
3.1 overview (understanding) of abstract classes
When we are doing subclass common function extraction, some methods are not embodied in the parent class. At this time, we need to abstract classes!
In Java, a method without a method body should be defined as an abstract method, and if there is an abstract method in a class, the class must be defined as an abstract class!
3.2 characteristics of abstract classes (memory)
-
Abstract classes and methods must be decorated with the abstract keyword
//Definition of abstract class public abstract class Class name {} //Definition of abstract methods public abstract void eat();
-
Abstract classes do not necessarily have abstract methods, and classes with abstract methods must be abstract classes
-
Abstract classes cannot be instantiated
-
Abstract classes can have constructors
-
Subclasses of abstract classes
Or override all abstract methods in an abstract class
Or it's an abstract class
3.3 cases of abstract classes (Applications)
-
Case requirements
Define cat and dog
Cat member method: eat (cat eats fish) drink (drink water...)
Dog member method: eat (dog eats meat) drink (drink water...)
-
Implementation steps
- There are common contents between cats and dogs, so an Animal should be extracted upward
- In the parent class Animal, the concrete implementation of eat method cannot be described clearly, so it is defined as an abstract method
- Abstract methods need to survive in abstract classes and define Animal as an abstract class
- Let Cat and Dog inherit Animal respectively and override eat method
- Create Cat and Dog objects in the test class and call the method test
-
code implementation
- Animals
public abstract class Animal { public void drink(){ System.out.println("drink water"); } public Animal(){ } public abstract void eat(); }
- Cats
public class Cat extends Animal { @Override public void eat() { System.out.println("Cats eat fish"); } }
- Dogs
public class Dog extends Animal { @Override public void eat() { System.out.println("Dogs eat meat"); } }
- Test class
public static void main(String[] args) { Dog d = new Dog(); d.eat(); d.drink(); Cat c = new Cat(); c.drink(); c.eat(); //Animal a = new Animal(); //a.eat(); }
3.4 formwork design mode
-
Design pattern
Design pattern is a set of code design experience that is repeatedly used, known by most people, classified and catalogued.
The purpose of using design patterns is to reuse code, make the code easier to be understood by others, ensure code reliability and program reusability. -
Template design mode
The abstract class as a whole can be seen as a template, and the things that cannot be determined in the template are defined as abstract methods
Let classes that use templates (classes that inherit abstract classes) override abstract methods to implement requirements -
Advantages of template design mode
The template has defined a general structure, and users only need to care about the functions they need to implement
-
Sample code
template class
/* Composition template class */ public abstract class CompositionTemplate { public final void write(){ System.out.println("<<My father>>"); body(); System.out.println("ah~ This is my father"); } public abstract void body(); }
Implementation class A
public class Tom extends CompositionTemplate { @Override public void body() { System.out.println("It was autumn, The wind is so lingering,In memory, " + "That day my father took me home from school by bike,My foot got stuck in the bicycle chain, Dad can't pedal,He got up and kicked..."); } }
Implementation class B
public class Tony extends CompositionTemplate { @Override public void body() { } /*public void write(){ }*/ }
Test class
public class Test { public static void main(String[] args) { Tom t = new Tom(); t.write(); } }
3.5 final (application)
-
Function of fianl keyword
- Final stands for the final meaning. It can modify member methods, member variables and classes
-
final modifies the effects of classes, methods, and variables
-
fianl decorated class: this class cannot be inherited (it cannot have subclasses, but it can have parent classes)
-
final modifier method: this method cannot be overridden
-
final modifier variable: indicates that the variable is a constant and cannot be assigned again
-
Variables are basic types, and values cannot be changed
-
Variables are reference types. What cannot be changed is the address value, but the contents of the address can be changed
-
give an example
public static void main(String[] args){ final Student s = new Student(23); s = new Student(24); // error s.setAge(24); // correct }
-
-
3.6 improvement (application) of information management system using abstract classes
-
demand
- Using the idea of abstract class, the inputStudentInfo method in BaseStudentController is defined as an abstract method
- Use final to decorate methods that you do not want subclasses to override
-
code implementation
BaseStudentController class
public abstract class BaseStudentController { // Operator object private StudentService studentService = new StudentService(); private Scanner sc = new Scanner(System.in); // Open the student management system and display the student management system menu public final void start() { //Scanner sc = new Scanner(System.in); studentLoop: while (true) { System.out.println("--------Welcome to <student> management system--------"); System.out.println("Please enter your choice: 1.Add student 2.Delete student 3.Modify student 4.View student 5.sign out"); String choice = sc.next(); switch (choice) { case "1": // System.out.println("add"); addStudent(); break; case "2": // System.out.println("delete"); deleteStudentById(); break; case "3": // System.out.println("modification"); updateStudent(); break; case "4": // System.out.println("query"); findAllStudent(); break; case "5": System.out.println("Thank you for using the student management system, bye!"); break studentLoop; default: System.out.println("Your input is incorrect, Please re-enter"); break; } } } // Modify student methods public final void updateStudent() { String updateId = inputStudentId(); Student newStu = inputStudentInfo(updateId); studentService.updateStudent(updateId, newStu); System.out.println("Modified successfully!"); } // Delete student method public final void deleteStudentById() { String delId = inputStudentId(); // 3. Call the deleteStudentById in the operator to delete the student according to the id studentService.deleteStudentById(delId); // 4. Prompt deletion succeeded System.out.println("Delete succeeded!"); } // View student methods public final void findAllStudent() { // 1. Call the acquisition method in the salesman to get the student's object array Student[] stus = studentService.findAllStudent(); // 2. Judge whether the memory address of the array is null if (stus == null) { System.out.println("No information found, Please add and try again"); return; } // 3. Traverse the array, obtain student information and print it on the console System.out.println("Student number\t\t full name\t Age\t birthday"); for (int i = 0; i < stus.length; i++) { Student stu = stus[i]; if (stu != null) { System.out.println(stu.getId() + "\t" + stu.getName() + "\t" + stu.getAge() + "\t\t" + stu.getBirthday()); } } } // Add student method public final void addStudent() { // StudentService studentService = new StudentService(); // 1. The keyboard receives student information String id; while (true) { System.out.println("Please enter student id:"); id = sc.next(); boolean flag = studentService.isExists(id); if (flag) { System.out.println("Student ID is occupied, Please re-enter"); } else { break; } } Student stu = inputStudentInfo(id); // 3. Pass the student object to the addStudent method in studentservice boolean result = studentService.addStudent(stu); // 4. Print success \ failure on the console according to the returned boolean type result if (result) { System.out.println("Added successfully"); } else { System.out.println("Add failed"); } } // Enter the student id on the keyboard public String inputStudentId() { String id; while (true) { System.out.println("Please enter student id:"); id = sc.next(); boolean exists = studentService.isExists(id); if (!exists) { System.out.println("You entered id non-existent, Please re-enter:"); } else { break; } } return id; } // Enter student information with keyboard // Opening and closing principle: open to extended content and close to modified content public abstract Student inputStudentInfo(String id); }
4. Code block
4.1 code block overview (understanding)
In Java, code enclosed with {} is called a code block
4.2 code block classification (understanding)
-
Local code block
-
Location: defined in method
-
Function: limit the life cycle of variables, release them as soon as possible, and improve memory utilization
-
Sample code
public class Test { /* Local code block Location: defined in method Function: limit the life cycle of variables, release them as soon as possible, and improve memory utilization */ public static void main(String[] args) { { int a = 10; System.out.println(a); } // System.out.println(a); } }
-
-
Construct code block
-
Location: defined outside the method in the class
-
Features: each time the construction method is executed, the code in the code block will be executed and executed before the construction method is executed
-
Function: extract the same code from multiple construction methods into the construction code block to improve the reusability of the code
-
Sample code
public class Test { /* Construction code block: Location: defined outside the method in the class Features: each time the construction method is executed, the code in the code block will be executed and executed before the construction method is executed Function: extract the same code from multiple construction methods into the construction code block to improve the reusability of the code */ public static void main(String[] args) { Student stu1 = new Student(); Student stu2 = new Student(10); } } class Student { { System.out.println("study hard"); } public Student(){ System.out.println("Null parameter construction method"); } public Student(int a){ System.out.println("Construction method with parameters..........."); } }
-
-
Static code block
-
Location: defined outside the method in the class
-
Features: it needs to be modified by the static keyword. It is loaded with the loading of the class, and it is only executed once
-
Function: do some data initialization operations during class loading
-
Sample code
public class Test { /* Static code block: Location: defined outside the method in the class Features: it needs to be modified by the static keyword. It is loaded with the loading of the class, and it is only executed once Function: do some data initialization operations during class loading */ public static void main(String[] args) { Person p1 = new Person(); Person p2 = new Person(10); } } class Person { static { System.out.println("I'm a static code block, I did"); } public Person(){ System.out.println("I am Person Null parameter construction method of class"); } public Person(int a){ System.out.println("I am Person Band of class...........Parameter construction method"); } }
-
4.3 code block improvement (application) of information management system
-
demand
Use static code blocks to initialize some student data
-
Implementation steps
- Define a static code block in the StudentDao class to initialize some student data
- Store the initialized student data in the student array
-
Sample code
StudentDao class
public class StudentDao { // Create an array of student objects private static Student[] stus = new Student[5]; static { Student stu1 = new Student("heima001","Zhang San","23","1999-11-11"); Student stu2 = new Student("heima002","Li Si","24","2000-11-11"); stus[0] = stu1; stus[1] = stu2; } // Add student method public boolean addStudent(Student stu) { // 2. Add students to the array //2.1 define the variable index as - 1, assuming that the array is full and there are no null elements int index = -1; //2.2 traverse the array, take out each element, and judge whether it is null for (int i = 0; i < stus.length; i++) { Student student = stus[i]; if(student == null){ index = i; //2.3 if it is null, let the index variable record the current index position, and use break to end the loop traversal break; } } // 3. Return the status of boolean type successfully added if(index == -1){ // Full return false; }else{ // If it is not full, it is added normally and returns true stus[index] = stu; return true; } } // View student methods public Student[] findAllStudent() { return stus; } public void deleteStudentById(String delId) { // 1. Find the index position of the id in the container int index = getIndex(delId); // 2. Overwrite the index position with null element stus[index] = null; } public int getIndex(String id){ int index = -1; for (int i = 0; i < stus.length; i++) { Student stu = stus[i]; if(stu != null && stu.getId().equals(id)){ index = i; break; } } return index; } public void updateStudent(String updateId, Student newStu) { // 1. Find updateId and the index position in the container int index = getIndex(updateId); // 2. Replace the index position with a new student object stus[index] = newStu; } }