I. What is inheritance?
Inheritance is a class-inheriting class, the inherited class is called a subclass, and the inherited name is called the parent class. The subclass has all the fields of the parent class, but the subclass can only call fields that have the parent class property as public and protected (in the same package the sub-class may invoke the parent class's Package access field).
Two. What is the meaning of inheritance?
Inheritance and composition are a quick way to implement code reuse, but there are different points.
Three. Syntax
Use keyword extends to:
Public class extends A {//B class inherits the Class A public staticvoid main (string[] args) { }}
After using the keyword extends Class B will automatically have all the methods and fields of Class A
Four. Keyword Super
When a subclass inherits a parent class, what should he do if he wants to invoke the method of calling the parent class in a method?
public class A { public v OID print () {System.out.println ( "Class A Print Method!) "); }}
Public class extends A {//B class inherits the Class A public void print () { print (); // you want to invoke the PRINNT function of the parent class, but such an operation would invert infinite recursion. } publicstaticvoid main (string[] args) { b b =new B (); B.print (); }}
Using the keyword super, you can call the method print of the parent class, which is the following code:
Public void print () { super. Print (); you want to invoke the PRINNT function of the parent class, but such an operation will invert infinite recursion }
Five. Initialization issues
1. Sequencing issues
In a logical order, if you want to initialize a subclass, you must first initialize the parent class, so the first thing to do in the constructor of the subclass is to initialize the parent class, as well as initialize the parent class or use the Super keyword
Public B () { Super(); }
2. Parameter issues
There are several parameters in the constructor of the parent class, so the constructors in the subclass also have several arguments, and the types are the same.
Public A (intlong longnum) { Super(); this. intnum = intnum; this. str = str; this. longnum = longnum; } Public int Long longnum) { super(intnum,str,longnum); }
Six. Overriding code for subclasses and adding new fields 3
In the subclass you can add new fields and then initialize them in the constructor.
The overriding code is a new definition of the parent class's function in the subclass, giving it new functionality.
Inheritance in Java