Chapter one: Inheritance
1. overview
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 they inherit that class.
Multiple classes can be called subclasses, while a single class is called a parent class, a superclass, or a base class.
2. definition
It means that the subclass inherits the methods and properties of the parent class, so that the subclass and the parent class share the methods and properties, and can access the non privatized properties and methods of the parent class.
3. benefits
Improved code reusability
The relationship between classes is the premise of polymorphism
In an inherited relationship, a subclass is a parent. In other words, a subclass can be treated as a parent. For example, if the parent class is an employee and the child class is an instructor, then the instructor is an employee. Relationship: is-a. Format of defining parent class: (a common class definition) public class parent class name{ // ... } Define the format of the subclass: public class subclass name extends parent class name{ // ... }
Note: in the parent-child relationship, if the name of a member variable is the same, there are two ways to access when creating a child object,
1. Access member variables directly through subclass objects
Whoever is on the left side of the equal sign will be the first to use. If not, look up
2. Access member variables indirectly through member methods
If the method belongs to anyone, it will be used first. If not, it will be looked up
Parent class
public class Fu { int numFu = 10; int num = 100; public void methodFu() { // It is used in this class. It will not look down for subclasses System.out.println(num); } }
Subclass
public class Zi extends Fu { int numZi = 20; int num = 200; public void methodZi() { // Because there is num in this class, we use this class's num here System.out.println(num); } }
Test method:
public class Demo01ExtendsField { public static void main(String[] args) { Fu fu = new Fu(); // Create parent object System.out.println(fu.numFu); // You can only use the things of the parent class, and there is no content of the child class System.out.println("==========="); Zi zi = new Zi(); System.out.println(zi.numFu); // 10 System.out.println(zi.numZi); // 20 System.out.println("==========="); // Whoever is on the left side of the equal sign will take precedence System.out.println(zi.num); // Priority subclass, 200 // System.out.println(zi.abc); / / there is no such thing. Compile and report an error! System.out.println("==========="); // This method is subclass. It takes precedence over subclass, and there is no further upward search zi.methodZi(); // 200 // This method is defined in the parent class, zi.methodFu(); // 100 } }
Be careful:
A parent class cannot call something of a child class
But a subclass can call the
Duplicate member method name - override
If a member method with the same name appears in the parent class of a subclass, the access at this time is a special case, which is called method rewrite
Method overwrite: as like as two peas in the subclass, the same method is applied to the parent class (the return value type, the method name and the parameter list are the same), and the coverage effect will also appear, also known as rewriting or copying. The declaration is unchanged and re implemented.
class Fu { public void show() { System.out.println("Fu show"); } } class Zi extends Fu { //The subclass overrides the show method of the parent class public void show() { System.out.println("Zi show"); } } public class ExtendsDemo05{ public static void main(String[] args) { Zi z = new Zi(); // There is a show method in the subclass. Only the rewritten show method is executed z.show(); // Zi show } }
Relationship between rewriting and overloading
In the inheritance relationship of parent-child classes, create child class objects and access the rules of member methods:
Whoever the created object is, it will be used first. If not, it will be looked up.
matters needing attention:
No matter it is a member method or a member variable, if it does not all look up to the parent class, it will never look down to the child class.
Override
Concept: in the inheritance relationship, the name of the method is the same, so is the parameter list.
Override: the name of the method is the same as that of the parameter list. Overwrite.
Overload: the name of the method is the same, and the parameter list is different.
Overriding and rewriting feature of method: if a subclass object is created, the subclass method is preferred.
//Parent class public class Fu { public void methodFu() { System.out.println("Parent method execution!"); } public void method() { System.out.println("Execution of method with duplicate name of parent class!"); } } //Subclass public class Zi extends Fu { public void methodZi() { System.out.println("Subclass method execution!"); } public void method() { System.out.println("Subclass duplicate method execution!"); } } public static void main(String[] args) { Zi zi = new Zi(); zi.methodFu();//Parent method execution! zi.methodZi();//Subclass method execution! // The new subclass object is created, so the subclass method is preferred zi.method();//Subclass duplicate method execution! }
Method rewriting considerations
1. It must be ensured that the names of methods and parameter lists between parent and child classes are the same. @Override: written in front of the method to detect whether the override is valid. Even if this annotation is not written, as long as it meets the requirements, it is also the correct method override. 2. The return value of the subclass method must be [less than or equal to] the return value range of the parent method. Small extension hint: java.lang.Object class is the highest common parent class (ancestor class) of all classes, and java.lang.String is the subclass of Object. 3. The permission of the subclass method must be [greater than or equal to] the permission modifier of the parent method. Tips for small extension: public > protected > (default) > private Note: (default) it's not the keyword default, but nothing. Leave it blank.
Application of rewriting
Subclasses can define their own behavior as needed. It not only follows the function name of the parent class, but also re implements the parent class method according to the needs of the child class, so as to extend and enhance. For example, the new mobile phone adds the function of caller ID, the code is as follows:
// Original old cell phone public class Phone { public void call() { System.out.println("Phone"); } public void send() { System.out.println("Send message"); } public void show() { System.out.println("Display number"); } }
// Define a new mobile phone and use the old mobile phone as the parent class public class NewPhone extends Phone { @Override public void show() { super.show(); // Take the show method of the parent class and reuse it // Add more content to your subclass System.out.println("Display name"); System.out.println("Show Faces"); } }
public static void main(String[] args) { Phone phone = new Phone(); phone.call(); phone.send(); phone.show(); //Call and SMS display number System.out.println("=========="); NewPhone newPhone = new NewPhone(); newPhone.call();//Phone newPhone.send();//Send message newPhone.show(); //Display number, name and picture }
In the inheritance relationship, the access characteristics of parent-child class construction methods are as follows:
-
There is a default implicit "super()" call in the subclass construction method, so it must be a subclass construction called first and then executed.
-
Subclass construction can call parent class overload construction through super keyword.
-
Super's parent class construction call must be the first statement of the child class construction method. A subclass construct cannot call more than one super construct.
Summary: the subclass must call the parent class to construct a method. If it is not written, it will give super(); if it is written, it will use the specified super call. There can only be one super, and it must be the first.
public class Fu { public Fu() { System.out.println("Parent nonparametric construction"); } public Fu(int num) { System.out.println("Parent class has parameter construction!"); } }
public class Zi extends Fu { public Zi() { super(); // When calling the parent class no parameter construction method // super(20); / / calling the construction method of parent class overload System.out.println("Subclass construction method!"); } public void method() { // super(); / / wrong writing! Only a subclass constructor can call a parent constructor. } }
public class Demo01Constructor { public static void main(String[] args) { Zi zi = new Zi(); } //output // Parent nonparametric construction //Subclass construction method! }
Be careful:
Only the constructor of a subclass can call the constructor of a parent class
There are three ways to use the super keyword:
- In the member method of a subclass, access the member variable of the parent class.
- In the member method of a subclass, access the member method of the parent class.
- In the construction method of the subclass, access the construction method of the parent class.
public class Fu { int num = 10; public void method() { System.out.println("Parent class method"); } }
public class Zi extends Fu { int num = 20; public Zi() { super();//Call parent class no parameter construction } public void methodZi() { System.out.println(super.num); // num in the parent class } public void method() { super.method(); // Access method in parent class System.out.println("Subclass method"); } }
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 calls it will represent it)
The super keyword is used to access the content of the parent class, while the this keyword is used to access the content of this class.
There are three ways to use this:
- In the member method of this class, access the member variable of this class.
- In the member method of this class, access another member method of this class.
- In the constructor of this class, access another constructor of this class.
Note in the third usage:
A. this(...) )The call must also be the first statement, the only one, that constructs the method.
B. super and this can't be used at the same time.
public class Fu { int num = 30; }
public class Zi extends Fu { int num = 20; public Zi() { // super(); / / this line is no longer free this(123); // The nonparametric construction of this class calls the parametric construction of this class // this(1, 2); / / wrong writing! } public Zi(int n) { this(1, 2); } public Zi(int n, int m) { } public void showNum() { int num = 10; System.out.println(num); // local variable System.out.println(this.num); // Member variables in this class System.out.println(super.num); // Member variables in the parent class } public void methodA() { System.out.println("AAA"); } public void methodB() { this.methodA(); System.out.println("BBB"); } }
//Parent class public class Fu { int num = 10; public void method() { System.out.println("Parent class method"); } } //Subclass public class Zi extends Fu { int num = 20; @Override public void method() { super.method(); // Parent method called System.out.println("Subclass method"); } public void show() { int num = 30; System.out.println(num); // 30 System.out.println(this.num); // This keyword is used to call the num of this class System.out.println(super.num); // The super keyword is used to call the parent class's } } //Test class public class Demo { public static void main(String[] args) { Zi zi = new Zi(); zi.show(); zi.method(); } //Output: //30 //20 //10 //Parent class method //Subclass method }
Characteristics of inheritance
- 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
- Java supports multiple inheritance (inheritance system)
class A{} class B extends A{} class C extends B{}
Be careful:
The top-level parent class is the Object class. By default, all classes inherit Object as the parent class.
- Subclass and superclass are relative concepts.
Chapter two: abstract classes
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 has meaning, while the method body has no meaning. We call a method without a method subject an abstract method. According to Java syntax, a class containing abstract methods is an abstract class
The method in the parent class is rewritten by the subclass, and the subclass implementation is different. The topic of the parent class has no meaning. This method is called abstract method and the parent class is called abstract class
How to use abstract classes and abstract methods:
- You cannot create a new abstract class object directly.
- A subclass must be used to inherit the abstract parent.
- The subclass must override all abstract methods that override the abstract parent.
Override override (Implementation): the subclass removes the abstract keyword from the abstract method, and then fills in the method body brace. - Create subclass objects for use.
//Parent class public abstract class Animal { // This is an abstract method that represents eating, but the specific eating (the content of the braces) is uncertain. public abstract void eat(); // This is the normal membership method // public void normalMethod() { // // } //Subclass public class Cat extends Animal { @Override public void eat() { System.out.println("Cats eat fish.");//Subclass override parent method } } } //Test class public class DemoMain { public static void main(String[] args) { // Animal animal = new Animal(); / / wrong way to write! Cannot create abstract class object directly Cat cat = new Cat(); cat.eat(); } }
Be careful:
Abstract classes cannot be called directly
If an abstract class exists in a class, it must be an abstract class
Use of abstract classes
1. All the subclasses that inherit the abstract class must override the methods of the parent class. Otherwise, the subclass must also be declared as an abstract class. Finally, there must be a subclass to implement these methods. Otherwise, objects cannot be created from the original parent class to the final subclass, which is meaningless
2. An abstract class does not necessarily contain abstract methods,
Just make sure that the class of the abstract method is an abstract class.
In this way, there are no abstract classes with abstract methods, nor can objects be created directly, which is useful in some special scenarios.
public abstract class MyAbstract { }
//Parent class public abstract class Fu { public Fu() { System.out.println("Abstract parent class construction method execution!"); } public abstract void eat(); } //Subclass public class Zi extends Fu { public Zi() { // super(); System.out.println("Subclass construction method execution"); } @Override public void eat() { System.out.println("Dinner"); } } //Test class public class DemoMain { public static void main(String[] args) { Zi zi = new Zi(); zi.eat(); } } //Output result //Abstract parent class construction method execution! //Subclass construction method execution //Dinner
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.
- 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. - In an abstract class, there can be construction methods that are used to initialize 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. - Abstract classes do not necessarily contain abstract methods, but classes with abstract methods must be abstract classes.
An abstract class that does not contain an abstract method. The purpose is not to let the caller create the class object, which is usually used for some special class structure design. - The subclass of an abstract class must override all the abstract methods in the abstract parent class. 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
Case: group leader sends ordinary red packets
User class:
public class User { private String name; // Full name private int money; // Balance, that is, the amount of money the current user owns public User() { } public User(String name, int money) { this.name = name; this.money = money; } // How much is the current user public void show() { System.out.println("My name is:" + name + ",How much do I have:" + money); } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getMoney() { return money; } public void setMoney(int money) { this.money = money; } }
Group master class:
// Class of group owners public class Manager extends User { public Manager() { } public Manager(String name, int money) { super(name, money); } public ArrayList<Integer> send(int totalMoney, int count) { // First, a collection is needed to store the amount of several red packets ArrayList<Integer> redList = new ArrayList<>(); // First of all, let's see how much money the owners have int leftMoney = super.getMoney(); // Group master current balance if (totalMoney > leftMoney) { System.out.println("Sorry, your credit is running low"); return redList; // Return empty set } // To deduct money is to reset the balance super.setMoney(leftMoney - totalMoney); // Red packets need to be split into count shares on average int avg = totalMoney / count; int mod = totalMoney % count; // The remainder, which is the change left // It's in the last red bag, except for the unopened change // Let's put the red envelopes one by one into the collection for (int i = 0; i < count - 1; i++) { redList.add(avg); } // Last red bag int last = avg + mod; redList.add(last); return redList; } }
Common member class:
public class Member extends User { public Member() { } public Member(String name, int money) { super(name, money); } public void receive(ArrayList<Integer> list) { // Take one from many red envelopes and give it to myself. // Get index number in a set randomly int index = new Random().nextInt(list.size()); // According to the index, delete from the collection and get the deleted red packet. Give it to myself int delta = list.remove(index); // How much money do members have int money = super.getMoney(); // Add and reset back super.setMoney(money + delta); } }
Test class:
public static void main(String[] args) { Manager manager = new Manager("Group owner", 100); Member one = new Member("member A", 0); Member two = new Member("member B", 0); Member three = new Member("member C", 0); manager.show(); // 100 one.show(); // 0 two.show(); // 0 three.show(); // 0 System.out.println("==============="); // The group leader will pay 20 yuan in total and divide it into three red envelopes ArrayList<Integer> redList = manager.send(20, 3); // Three ordinary members receive red envelopes one.receive(redList); two.receive(redList); three.receive(redList); manager.show(); // 100-20=80 // 6. 6, 8, randomly assigned to three people one.show(); two.show(); three.show(); }