Content today
1. Three characteristics inheritance
2. Method rewrite
3.super keyword
4.this keyword
5. abstract class
Teaching objectives
1. Be able to interpret class name as parameter and return value type
2. Be able to write out the inheritance format of the class
3. Be able to say the characteristics of inheritance
4. Be able to say the member characteristics of subclass calling parent class
5. Be able to say the concept of method rewrite
6. Be able to say the problems that super can solve
7. Describe the concept of abstract methods
8. Write the format of abstract class
9. Write the format of abstract method
10. Be able to say the existence meaning of the abstract method of the parent class
11. Be able to complete the code logic of the red packet case
Chapter one succession
1.1 overview
origin
When there are the same properties and behaviors in multiple classes, extract these contents into a single class, then multiple classes do not need to define these properties and behaviors, as long as
Just inherit that class. As shown in the figure:
Among them, multiple classes can be called subclasses, and the single class is called the parent class, superclass or base class.
Inheritance describes the relationship between things, which is the relationship of is-a. For example, rabbit in the picture belongs to herbivore, herbivore belongs to animal
Things. It can be seen that the parent class is more general and the child class is more specific. Through inheritance, we can form a relationship system among many things.
Definition
Inheritance: a subclass inherits the properties and behaviors of the parent class, so that the subclass object has the same properties and behaviors as the parent class. Subclass can be directly
Access non private properties and behaviors in the parent class.
benefit
1. Improve code reusability.
2. The relationship between classes is the premise of polymorphism.
1.2 inherited format
By using the extends keyword, you can declare that a subclass inherits another parent class. The definition format is as follows:
class parent{ ... } Class subclass extends parent class{ ... }
The code of inheritance demonstration is as follows:
/* * Define Employee as parent */ class Employee { String name; // Definition name attribute // Define how employees work public void work() { System.out.println("Do your best"); } } /* * Define instructor class Teacher inherits Employee class */ class Teacher extends Employee { // Define a print name Method public void printName() { System.out.println("name=" + name); } } /* * Define test class */ public class ExtendDemo01 { public static void main(String[] args) { // Create an instructor class object Teacher t = new Teacher(); // For this Employee class name Property to assign t.name = "Xiao Ming"; // Call the employee's printName()Method t.printName(); // name = Xiao Ming // call Teacher Class inherited work()Method t.work(); // Do your best } }
1.3 inherited features - member variables
When there is a relationship between classes, what effect does the member variables in each class have?
Member variable does not have the same name
If there is a member variable with different name in the parent class of the subclass, the access will not be affected. The code is as follows:
class Fu { // Fu Member variable in. int num = 5; }
class Zi extends Fu { // Zi Member variables in int num2 = 6; // Zi Member methods in public void show() { // Access the num, System.out.println("Fu num=" + num); // Inherited, so direct access. // Access to the num2 System.out.println("Zi num2=" + num2); } } class ExtendDemo02 { public static void main(String[] args) { // Create a subclass object Zi z = new Zi(); // Call the show Method z.show(); } } //Results: Fu num = 5 Zi num2 = 6
Duplicate member variable name
If a member variable with the same name appears in the parent class of a subclass, then the access will be affected. The code is as follows:
class Fu { // Fu Member variable in. int num = 5; } class Zi extends Fu { // Zi Member variables in int num = 6; public void show() { // Access the num System.out.println("Fu num=" + num); // Access to the num System.out.println("Zi num=" + num); } } class ExtendsDemo03 { public static void main(String[] args) { // Create a subclass object Zi z = new Zi(); // Call the show Method z.show(); } } //Results: Fu num = 6 Zi num = 6
When there is a member variable with the same name in the child parent class, when the child class needs to access the non private member variable in the parent class, it needs to use the super keyword to modify
A member variable of the parent class, similar to this.
Use format:
super. Parent class member variable name
The subclass method needs to be modified. The code is as follows:
class Zi extends Fu { // Zi Member variables in int num = 6; public void show() { //Access the num System.out.println("Fu num=" + super.num); //Access to the num System.out.println("Zi num=" + this.num); } } //Results: Fu num = 5 Zi num = 6
Tip: the member variables in the Fu class are not private and can be accessed directly in the subclass. If the member variable in the Fu class is private, the subclass cannot
Direct access. In general, when coding, we follow the principle of encapsulation, using private to decorate member variables, so how to access the private members of the parent class
What about variables? Yes! Public getXxx methods and setXxx methods can be provided in the parent class.
1.4 characteristics after inheritance member method
When there are relationships between classes, what are the effects of member methods in each class?
Member method does not have the same name
If a member method with different name appears in the parent class of a subclass, the call at this time has no effect. When an object calls a method, it first looks in the subclass to see if the
The corresponding method, if it exists in the subclass, it will execute the method in the subclass, if it does not exist in the subclass, it will execute the corresponding method in the parent class. The code is as follows:
class Fu { public void show() { System.out.println("Fu Class show Method execution"); } } class Zi extends Fu { public void show2() { System.out.println("Zi Class show2 Method execution"); } } public class ExtendsDemo04 { public static void main(String[] args) { Zi z = new Zi(); //Not in subclass show Method, but the parent method can be found to execute z.show(); z.show2(); } }
Duplicate name of member method -- override
If a member method with the same name appears in the parent class of a subclass, the access is a special case, which is called override.
Method rewrite: when a subclass has exactly the same way as the parent class (the return value type, the method name and the parameter list are the same), the coverage effect will appear.
Fruit, also known as rewriting or replication. The declaration is unchanged and re implemented.
The code is as follows:
class Fu { public void show() { System.out.println("Fu show"); } } class Zi extends Fu { //Subclass overrides the show Method public void show() { System.out.println("Zi show"); } } public class ExtendsDemo05 { public static void main(String[] args) { Zi z = new Zi(); // Subclass show Method, only the overridden show Method z.show(); // Zi show } }
Application of rewriting
Subclasses can define their own behavior as needed. It not only inherits the function name of the parent class, but also re implements the parent class method according to the needs of the child class.
And expand and enhance. For example, the new mobile phone adds the function of caller ID, the code is as follows:
class Phone { public void sendMessage() { System.out.println("Send message"); } public void call() { System.out.println("Phone"); } public void showNum() { System.out.println("Caller ID"); } } //Smart phones class NewPhone extends Phone { //Rewrite the caller ID function of the parent class, and add its own display name and picture function public void showNum() { //Call the existing function use of the parent class super super.showNum(); //Add your own unique display name and picture function System.out.println("Show caller name"); System.out.println("Show Faces"); } } public class ExtendsDemo06 { public static void main(String[] args) { // Create a subclass object NewPhone np = new NewPhone(); // Call the method inherited from the parent class np.call(); // Call subclass override method np.showNum(); } }
Tip: when overridden here, the super. Parent member method is used to call the member method of the parent class.
Matters needing attention
1. The subclass method covers the parent method, and the permission must be greater than or equal to the parent permission.
The 2. subclass method covers the parent class method, and the return value, function name and parameter list are exactly the same.
1.5 characteristics after inheritance -- construction method
When there is a relationship between classes, what effect does the construction method in each class have?
First, we need to recall two things: the definition format and function of the construction method.
1. The name of the constructor is the same as the class name. Therefore, a subclass cannot inherit a parent class construction method.
2. The function of construction method is to initialize member variables. Therefore, in the initialization process of a subclass, the initialization action of the parent class must be performed first. Construction of subclasses
There is a super() by default in the constructor, which means calling the constructor of the parent class. Only after the member variables of the parent class are initialized can they be used by the child class. generation
The code is as follows:
class Fu { private int n; Fu() { System.out.println("Fu()"); } } class Zi extends Fu { Zi() { // super(),Call the parent class constructor super(); System.out.println("Zi()"); } } public class ExtendsDemo07 { public static void main(String args[]) { Zi zi = new Zi(); } } //Output results: Fu() Zi()
1.6 super and this
Parent space takes precedence over child objects
Each time a subclass object is created, the parent space is initialized first, and then the subclass object itself is created. The purpose is that the subclass object contains its corresponding parent class null
If the parent member is not modified by private, the child can use the parent member at will. Code embodied in the construction of subclasses
When making a method call, make sure to call the constructor of the parent class first. The understanding is illustrated as follows:
Meaning of super and this
super: represents the storage space identifier of the parent class (which can be understood as the reference of the parent).
this: represents the reference of the current object (whoever invokes it represents).
Use of super and this
1. Visiting members
This. Member variable ‐ of this class super. Member variable This. Member method name () - of this class super. Member name () - of parent class
The code is as follows:
class Animal { public void eat() { System.out.println("animal : eat"); } } class Cat extends Animal { public void eat() { System.out.println("cat : eat"); } public void eatTest() { this.eat(); super.eat(); // this Call methods of this class // super Call the method of the parent class } } public class ExtendsDemo08 { public static void main(String[] args) { Animal a = new Animal(); a.eat(); Cat c = new Cat(); c.eatTest(); } } //The output result is: animal: eat cat: eat animal: eat
2. Access construction method
this(...) - construction method of this class The construction method of super(...) - parent class
Each construction method of a subclass has a default super (), which calls the null parameter construction of the parent class. Calling the parent class construction manually overrides the default super().
Both super() and this() must be on the first line of the constructor, so they cannot appear at the same time.
1.7 characteristics of inheritance
1. Java only supports single inheritance, not multiple inheritance.
//A class can only have one parent, not more than one parent. class C extends A {} //ok class C extends A, B... //error
2. Java supports multi-level inheritance (inheritance system).
class A {} class B extends A {} class C extends B {}
The top-level parent class is the Object class. By default, all classes inherit Object as the parent class.
3. Subclass and superclass are relative concepts.
Chapter II Abstract Classes
2.1 overview
origin
The methods in the parent class are rewritten by its subclasses, and the implementation of each subclass is different. Then the method declaration and method body of the parent class, only the declaration and
Meaning, while the subject of method has no meaning. We call a method without a method subject an abstract method. Java syntax, including abstract methods
The class of is an abstract class.
Definition
Abstract method: method without method body.
Abstract class: a class containing abstract methods.
2.2 abstract usage format
Abstract method
The abstract keyword is used to modify the method, which becomes an abstract method. The abstract method contains only one method name, but no method body.
Definition format:
Modifier abstract returns the value type method name (parameter list);
Code example:
public abstract void run();
abstract class
If a class contains abstract methods, the class must be abstract.
Definition format:
abstract class name{ }
Code example:
public abstract class Animal { public abstract void run(); }
Use of abstraction
Subclasses that inherit abstract classes must override all abstract methods of the parent class. Otherwise, the subclass must also be declared as an abstract class. Finally, a subclass must implement the parent
Class. Otherwise, objects cannot be created from the original parent class to the final child class, which is meaningless.
Code example:
public class Cat extends Animal { public void run() { System.out.println("Kitten is walking on the wall~~~"); } } public class CatTest { public static void main(String[] args) { // Create a subclass object Cat c = new Cat(); // call run Method c.run(); } } //Output results: //Kitten is walking on the wall~~~
At this time, method rewriting is the child class's complete implementation of the parent class's abstract method. We also call this method rewriting operation the implementation method.
2.3 precautions
As for the use of abstract classes, the following are the details to be paid attention to in syntax. Although there are many entries, if you understand the essence of abstraction, you don't need to memorize them.
1. Abstract classes cannot create objects. If they are created, compilation fails and an error is reported. Only objects with non Abstract subclasses can be created.
Understanding: suppose that the object of the abstract class is created and the abstract method is called, but the abstract method has no concrete method body and no meaning.
2. In an abstract class, there can be construction methods for initializing the members of the parent class when a child class creates an object.
Understanding: in the construction methods of subclasses, there is a default super(), which needs to access the construction methods of the parent class.
3. Abstract classes do not necessarily contain abstract methods, but the classes with abstract methods must be abstract classes.
Understanding: abstract classes that do not contain abstract methods are designed to prevent callers from creating such objects, which are usually used for some special class structure design.
4. For the subclass of an abstract class, all abstract methods in the abstract parent class must be overridden. Otherwise, the compilation fails and an error is reported. Unless the subclass is also an abstract class.
Understanding: if all abstract methods are not overridden, the class may contain abstract methods. After the object is created, it is meaningless to call abstract methods.
Chapter III comprehensive cases of inheritance
3.1 comprehensive case: general red packet issued by group
Group leader sends ordinary red packets. There are many members in a group. The group leader sends ordinary red packets to the members. Rules for ordinary red packets:
1. A sum of money from the group master shall be deducted from the balance of the group master, and divided into n equal parts on average for members to collect.
2. After the member receives the red packet, it is saved to the member balance.
According to the description, complete the definition of all classes in the case and the inheritance relationship between the specified classes, and complete the operation of sending red packets.
3.2 case study
According to the description analysis, the following inheritance system is obtained:
3.3 case realization
Define user class:
public class User { // Member variables private String username;// User name private double leftMoney;// balance // Construction method public User() {} public User(String username, double leftMoney) { this.username = username; this.leftMoney = leftMoney; } // get/set Method public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public double getLeftMoney() { return leftMoney; } public void setLeftMoney(double leftMoney) { this.leftMoney = leftMoney; } // How to present information public void show() { System.out.println("User name:" + username + " , The balance is:" + leftMoney + "element"); } }
Define group main class:
public class QunZhu extends User { // Add construction method public QunZhu() {} public QunZhu(String username, double leftMoney) { // adopt super Call the parent class constructor super(username, leftMoney); } /* The group leader sends red packets, that is, the amount of an integer is divided into several equal parts. 1.Get the group master balance, whether it is enough to send red packets. Cannot return null and prompt. Go ahead if you can. 2.Modify group master balance. 3.Split the red packet. 3.1.If it's divisible, average the score. 3.2.If it is not divisible, the remainder will be given to the last. */ public ArrayList < Double > send(int money, int count) { // Get group master balance double leftMoney = getLeftMoney(); if(money > leftMoney) { return null; } // Modify group master balance's setLeftMoney(leftMoney‐ money); // Create a collection,Save equal amount ArrayList < Double > list = new ArrayList < > (); // Expand 100 times,Equivalent to conversion into'branch'As a unit,Avoiding the loss of precision in decimal operation money = money * 100; // Amount of each int m = money / count; // Remainder not divisible int l = money % count; // Whether divided or not,n‐1 share,It's the same amount for each for(int i = 0; i < count‐ 1; i++) { // Shrink 100 times,Convert into 'element' list.add(m / 100.0); } // Judge whether to divide or not if(l == 0) { // Divisibility, Last amount,Same as each previous amount list.add(m / 100.0); } else { // Non divisibility, Amount of last copy,It's the previous amount+Amount of remainder list.add((m + l) / 100.00); } // Return set return list; } }
Define member classes:
public class Member extends User { public Member() {} public Member(String username, double leftMoney) { super(username, leftMoney); } // Open the red envelope,From the collection,Take out one copy at random,Save to your own balance public void openHongbao(ArrayList < Double > list) { // Establish Random object Random r = new Random(); // Generate a corner sign randomly int index = r.nextInt(list.size()); // Remove an amount //First floor, jinyanlong office building, West Jiancai Road, Changping District, Beijing Tel: 400-618-9090 //Define the test class: //After class, ask students to think about and complete the expansion needs. //Case extension: 1. What happens if the member's balance is not zero? Double money = list.remove(index); // Call the parent method directly,Set to balance setLeftMoney(money); } }
Define the test class:
public class Test { public static void main(String[] args) { // Create a group master QunZhu qz = new QunZhu("Group owner", 200); // Create a keyboard entry Scanner sc = new Scanner(); System.out.println("Please enter the amount:"); int money = sc.nextInt(); System.out.println("Please enter the number:"); int count = sc.nextInt(); // Sending red packets ArrayList < Double > sendList = s.send(money, count); // judge,If the balance is insufficient if(sendList == null) { System.out.println(" Sorry, your credit is running low..."); return; } // Create three members Member m = new Member(); Member m2 = new Member(); Member m3 = new Member(); // Open the red envelope m.openHongbao(sendList); m2.openHongbao(sendList); m3.openHongbao(sendList); // Display information qz.show(); m.show(); m2.show(); m3.show(); } }
Please think about and complete the expansion requirements by yourself.
Case extension:
1. What if the member's balance is not 0?
2. What if the group master wants to enter the amount with decimal?
ending...