inherit
One class can inherit from another class.
Derived classes (subclasses) inherit the methods and data members of the parent class.
Keyword: Subclass extends parent.
public class inherit { public static void main(String[] args) { //Wang Sicong a = new Wang Sicong (); System.out.println(a.money); a.show(); } } class Wang Jianlin { double money = 188.88; void show() { System.out.println("Not bad money"); } } class Sephirex Wang extends Wang Jianlin { }
Design examples
The main problem of inheritance is common extraction.
The characteristics of inheritance:
| Subclasses can have the "content" of their parent classes
| Subclasses can have their own "content"
Trucks and buses are automobiles. Their common features come from automobiles. They can also have their own characteristics.
public class Inheritance 2 { public static void main(String[] args) { } } class automobile { private int wheels; public int getWheels() { return wheels; } public void setWheels(int wheels) { this.wheels = wheels; } // ------------------------ public void Drive a car() { System.out.println("Driving"); } public void brake() { System.out.println("brake"); } } class Truck extends automobile { private int carryingCapacity; public int getCarryingCapacity() { return carryingCapacity; } public void setCarryingCapacity(int carryingCapacity) { this.carryingCapacity = carryingCapacity; } // ------------------------ public void Hanging box() { System.out.println("Hanging box"); } } class Bus extends automobile { private int seatings; public int getSeatings() { return seatings; } public void setSeatings(int seatings) { this.seatings = seatings; } // ------------------------ public void Reporting station(String str Station name) { System.out.println(str Station name + "Already arrived"); } }
Inheritance control
protected: Inheritance is available, even if it is not in the same package
private: No inheritance
this and super
this: My own
super: parent
|-|- super(): parent class construction method
|-|- Sup. XXX: A member of a parent class (method or variable)
public class This_and_Super { public static void main(String[] args) { S _s = new S(); _s.m();// Through subclass object directly, the method of subclass is called. _s.newNethod(); } } class F { protected int a = 1; protected void m() { System.out.println("F"); } } class S extends F { protected int a = 99; protected void m() { System.out.println("S"); } protected void newNethod() { System.out.println(super.a); System.out.println(this.a); System.out.println(a);// Direct invocation, is its own value // --------- super.m(); this.m(); m();// Direct invocation is your own method } }
super(): on the construction method
super must have, not write, also default, must first sentence, can only have one
(1) Default the parametric construction method of the parent class until the parametric construction method of the parent class is explicitly invoked.
Detailed: Whether the subclass constructor has parameters or not, the default is to execute the parent class's parametric constructor. [Hide a code: super()]
If you have to execute the parent class parametric constructor, use super (parameter list).
(2) Super (parent constructor) can only be placed in the constructor, and must be placed in the first sentence, so the parent constructor can not be called many times.
Test:
public class Tectonic sequence { public static void main(String[] args) { new S(); new S(1); new S(1L); } } class F { F() { System.out.println("Parent Class Construction Method"); } F(int a) { System.out.println("Parent Class Construction Method(Taking ginseng)"); } } class S extends F { S() { System.out.println("Subclass Construction Method\n"); } S(int a) { System.out.println("Subclass Construction Method(Taking ginseng)\n"); } S(long a) { super(1); System.out.println("Subclass Construction Method 2(Taking ginseng),Display a parametric construction method for calling the parent class\n"); } }
Parent Class Construction Method
Subclass Construction Method
Parent Class Construction Method
Subclass construction method (with parameters)
Parent class construction method (with parameters)
Subclass construction method 2 (with parameters), showing the parametric construction method that calls the parent class
this()
this(...) can also call its own other construction methods, but also must be placed in the first sentence, a construction method can only write one sentence.
class S2 extends F { S2() { this(100); } S2(int a) { this(100, 200); } S2(int a, int b) { } }
Thinking Question: Summarize the Usage of super and this
Override
Override: Method override, method override.
Subclasses can redefine methods inherited from parent classes. In the subclass method, the method of the parent class can be invoked by super.
- Two Same: Method Name Same, Formal Parameter List Same
- Two small: the return type is not bigger than the parent (big-handed loser), and the exception is not bigger than the parent (not to expand the scope)
- One is not small: access rights are not smaller than the parent class (public may not be abolished for private)
public class Rewrite { public static void main(String[] args) { Ostrich os = new Ostrich(); os.twitter(); os.fly(); } } class Bird { public void twitter() { System.out.println("wakuwaku"); } public void fly() { System.out.println("fly"); } } // Ostriches class Ostrich extends Bird { @Override// Write-free is also rewritten. Write-checked. If the method does not exist in the parent class, it will report an error. public void fly() { super.fly(); System.out.println("?Not at all."); } }
wakuwaku
fly
No?
The return type is not larger than the parent class (note: Object is the parent of String)
Access authority is no less than that of the patriarch (Yao Shun Yu, the end of the Zen concession system).
class Bird { public Object twitter() { return null; } public String fly() { return null; } } // Ostriches class Ostrich extends Bird { public String twitter() {// The parent class is Object and the child class is String. No problem. return null; } @Override// Parent class return type String, changed to Object public Object fly() {// The return type is incompatible with Bird.fly() return null; } } // Pigeons class Pigeon extends Bird { @Override private String fly() {// The parent class is public instead of private // Cannot reduce the visibility of the inherited method from Bird return null; } }
Rewritten application scenarios:
For existing classes, try not to modify the code, but to derive a new subclass and rewrite the response method.
final (no modification)
Final Modified Class: This class cannot be inherited (such as String class)
Final Modification: This method cannot be overridden
Final modifier variable: cannot be reassigned
Constants in Java:
public static final int CHANG_LIANG = 10;
The Disadvantage of Inheritance
Inheritance is an important means to achieve class reuse, but inheritance can destroy encapsulation.
Each class should encapsulate its internal information and implementation details, exposing only the necessary methods for other classes to use. However, subclasses can directly access the internal information of the parent class, and even rewrite the methods of the parent class, which increases the coupling between the subclass and the parent class and destroys the encapsulation.
When designing a parent class, the following principles should be followed:
- Try to set the member variables of the parent class to private.
- Minimize the access rights of the methods, and avoid sharing them privately.
- The method that you do not want to be overridden by a subclass is set to final.
- Do not call methods overridden by subclasses in the constructor of the parent class.
In the following code, the construction method of the parent class A, which calls the overridden method() method, because the parent class construction method is executed first, and the method() method it calls is overridden by the subclass. There is no variable s at this time, so s is null.
class A { public A() { System.out.println("A Construction method"); method(); this.method(); } public void method() { System.out.println("A method"); } } class B extends A { public String s = "Subclass variables"; public void method() { System.out.println("B method: " + s); } } public class TestInstanceOf { public static void main(String[] args) { B b = new B(); } }