java inheritance starts with "My father is Li Gang"

Preface This paper mainly explains the inheritance of java in many ways, in order to make beginners easy to understand. As for "My father is Li Gang", the landlord does not know who is Li Gang anyway. @[toc]

1. Overview of Inheritance

1.1. Origin of Inheritance

For a simple reason: when there are identical attributes and behaviors in multiple classes, extracting them into a single class eliminates the need for multiple classes to define these attributes and behaviors.

Inheritance describes the ownership relationship between things, which is A-A relationship.

1.2. Definition of Inheritance

Inheritance: A subclass inherits the attributes and behaviors of the parent class so that the subclass object has the same attributes and behavior as the parent class.Subclasses have direct access to non-private properties and behaviors in the parent class.

It is further declared here that <font color=red>parent class </font>is also known as <font color=red>superclass </font>or <font color=red>base class </font>.The <font color=red>subclass </font>is also called <font color=red>derived class </font>which is very basic!

1.3. Advantages of Inheritance

  1. Improve code reuse.
  2. The relationship between classes paves the way for polymorphism (it doesn't matter if you don't understand it, then I'll write another polymorphic article)

Although there are many advantages to inheritance, Java <font color=red>only supports single inheritance, not multiple inheritance.</font>

1.4. Inherited Format

With the extends keyword, you can declare that one subclass inherits another parent class in the following format:

  class parent {
   ... 
   }
   Class subclass extends parent class { 
   ... 
   } 

2. About member variables after inheritance

What happens to the member variables in the classes when a relationship is created between them?There are two ways to start with member variables after inheritance: one is not renaming member variables, the other is renaming member variables.

2.1, Member variable not renamed

Access is unaffected if an unnamed member variable appears in the parent of the child class.The code is as follows:

  class liGang {
        // Member variables in the parent class.
       String name ="Li Gang";//---------------------------------------- The parent member variable is name
    }
    class LiXiaoGang extends liGang {
        // Member variables in subclasses
        String name2 ="Li Xiaogang";//-------------------------------- Subclass member variable is name2
        // Membership methods in subclasses
        public void show() {
            // Access the name in the parent class,
            System.out.println("My father is"+name);
            // Inherited, so access directly.
            // Accessing name2 in subclasses
            System.out.println("I am"+name2);
        }
    }
public class Demo {
        public static void main(String[] args) {
            // Create Subclass Object
            LiXiaoGang z = new LiXiaoGang();
            // Call show method in subclass
            z.show();
        }
    }
    //Demonstration Result: My father is Li Gang and I am Li Xiaogang

2.2, member variable rename

Access is affected if a member variable with a duplicate name appears in the parent of the child class.The code is as follows:

class liGang {
        // Member variables in the parent class.
       String name ="Li Gang";//---------------------------------------- The parent member variable is name
    }
    class LiXiaoGang extends liGang {
        // Member variables in subclasses
        String name ="Li Xiaogang";//-------------------------------- Subclass member variable is also name
        // Membership methods in subclasses
        public void show() {
            // Access the name in the parent class,
            System.out.println("My father is"+name);
            // Inherited, so access directly.
            // Accessing name2 in subclasses
            System.out.println("I am"+name);
        }
    }
public class Demo {
        public static void main(String[] args) {
            // Create Subclass Object
            LiXiaoGang z = new LiXiaoGang();
            // Call show method in subclass
            z.show();
        }
    }
    //Demonstration Result: My father is Li Xiaogang and I am Li Xiaogang


When a member variable with the same name appears in the child parent class, the super keyword is used when accessing a non-private member variable in the parent class in the child class. As for modifying a parent member variable, this is similar to what you've learned before.Use the format super.parent member variable name

this represents the current object, super represents the parent object, similar in usage!

class liGang {
        // Member variables in the parent class.
       String name ="Li Gang";
    }
    class LiXiaoGang extends liGang {
        // Member variables in subclasses
        String name ="Li Xiaogang";
        // Membership methods in subclasses
        public void show() {
            // Access the name in the parent class,
            System.out.println("My father is"+super.name);
            // Inherited, so access directly.
            // Accessing name2 in subclasses
            System.out.println("I am"+this.name);  //Of course this can be omitted
        }
    }
public class Demo {
        public static void main(String[] args) {
            // Create Subclass Object
            LiXiaoGang z = new LiXiaoGang();
            // Call show method in subclass
            z.show();
        }
    }
    //Demonstration Result: My father is Li Gang and I am Li Xiaogang

2.3. A Question on Membership Variables in Inheritance

Have you thought about such a question, classmate?If a member variable in a parent class Non-private: Direct access in subclasses. Private: Subclasses are not directly accessible.The following: Of course, students should experience the process of compiling a newspaper missed by themselves. It's hard to see the pictures without experiencing it. ~Thank you, you have no charm to place here and unreasonable demands. I'm Buddha, OK ~

  class liGang2 {
        // Member variables in the parent class.
        private String name ="Li Gang";

    }
    class LiXiaoGang2 extends liGang2 {
        // Member variables in subclasses
        String name ="Li Xiaogang";
        // Membership methods in subclasses
        public void show() {
            // Access the name in the parent class,
            System.out.println("My father is"+super.name);//------ Compilation failure does not allow direct access to parent private properties (member variables)
            // Inherited, so access directly.
            // Accessing name2 in subclasses
            System.out.println("I am"+this.name);  //Of course this can be omitted
        }
    }
public class PrivateVariable {
        public static void main(String[] args) {
            // Create Subclass Object
            ExtendDemo.LiXiaoGang z = new ExtendDemo.LiXiaoGang();
            // Call show method in subclass
            z.show();
        }
    }

Usually when coding in development, we follow the principle of encapsulation and use private to modify member variables, so how do we access private member variables of the parent class?In fact, this is the time to provide the common getXxx and setXxx methods in the parent class.The code is as follows:

class liGang {
        // Member variables in the parent class.
      private String name ="Li Gang";

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }
    }
    class LiXiaoGang extends liGang {
        // Member variables in subclasses
        String name ="Li Xiaogang";
        // Membership methods in subclasses
        public void show() {
            // Access the name in the parent class,
            System.out.println("My father is"+super.getName());
            // Inherited, so access directly.
            // Accessing name2 in subclasses
            System.out.println("I am"+this.name);  //Of course this can be omitted
        }
    }
public class Demo {
        public static void main(String[] args) {
            // Create Subclass Object
            LiXiaoGang z = new LiXiaoGang();
            // Call show method in subclass
            z.show();
        }
    }
    //Demonstration Result: My father is Li Gang and I am Li Xiaogang

The analysis is as follows:

3. Membership methods after inheritance

Now that you've analyzed the member variables, let's analyze the member method together. Think about what happens when relationships arise between classes and the member methods within them.Again, there are two ways to analyze this.

3.1. Membership methods do not rename

If an unrenamed member method appears in the parent of the child class, the call will have no effect.When an object invokes a method, it first looks for a corresponding method in the subclass. If a method exists in the subclass, it executes the method in the subclass, and if no method exists in the subclass, it executes the corresponding method in the parent class.The code is as follows:

 class liGang3 {
        // Member method in parent class.
       public void zhuangRen1(){//------------------------------------ Parent method name zhuangRen1
           System.out.println("My name is Li Gang. I didn't bump into you. Don't catch me. I don't know Li Xiaogang.");
       }
    }
    class LiXiaoGang3 extends liGang3 {

        // Membership methods in subclasses
        public void zhuangRen() {//---------------------------------- Subclass method name zhuangRen
            System.out.println("You can tell me that my father is Li Gang");  
        }
    }
    public class MemberMethod {
        public static void main(String[] args) {
            // Create Subclass Object
            LiXiaoGang3 liXiaoGang = new LiXiaoGang3();
            // Call show method in subclass
            liXiaoGang.zhuangRen();
            liXiaoGang.zhuangRen1();
        }
    }
    
//Print result: You can tell me that my father is Li Gang
        //My name is Li Gang. I didn't bump into you. Don't catch me. I don't know Li Xiaogang.

3.2, Member Method Rename [Method Override]

Membership method renames can generally be divided into two cases:

1. Method names have the same return value type, but parameter lists are different (take precedence over subclasses, and go to parent if not found) 2. Method name, return value type, parameter list are all the same, that is, override

Here we will focus on method override: when the same method as the parent class appears in a subclass (return value type, method name and parameter list are the same), the <font color=red>override </font>effect will appear, also known as <font color=red>override </font>or <font color=red>override </font>.Statement unchanged, re-implemented.The code is as follows:

    class liGang3 {
        // Member method in parent class.
       public void zhuangRen(int a){
           System.out.println("My name is Li Gang. I didn't bump into you. Don't catch me");
       }
    }
    class LiXiaoGang3 extends liGang3 {

        // Membership methods in subclasses
        public void zhuangRen(int a) {
            System.out.println("You can tell me that my father is Li Gang");
        }
    }
    public class MemberMethod {
        public static void main(String[] args) {
            // Create Subclass Object
            LiXiaoGang3 liXiaoGang = new LiXiaoGang3();
            // Call zhuangRen method in subclass
            liXiaoGang.zhuangRen(1);

        }
    }
    //Result Print: You can tell me that my father is Li Gang

3.3. Significance of overriding methods in inheritance

Subclasses can define their own behavior as needed.It inherits the function name of the parent class and reimplements the parent method as required by the child class, thereby expanding and enhancing.For example, Li Gang can drive a car, Li Xiaogang is a cow, and expanding enhancements in the parent class can also run into people while driving. The code is as follows:

 class liGang3 {
        // Member method in parent class.
       public void kaiChe(){
           System.out.println("I can drive");
       }
    }
    class LiXiaoGang3 extends liGang3 {
        // Membership methods in subclasses
        public void kaiChe(){
            super.kaiChe();
            System.out.println("I'll bump into people");
            System.out.println("I can also bump into two mothers-in-law");
        }
    }
    public class MemberMethod {
        public static void main(String[] args) {
            // Create Subclass Object
            LiXiaoGang3 liXiaoGang = new LiXiaoGang3();
            // Call zhuangRen method in subclass
            liXiaoGang.kaiChe();

//Print results: I drive
		   //I'll bump into people
		   //I can also bump into two mothers-in-law
        }
    }

Don't know if your classmates found it, the above code uses super.kaiChe(); super.parent member method, which means calling the member method of the parent class.

Last rewrite must pay attention to these points:

1. When a method is overridden, the method name and the parameter list must be identical. 2. When a subclass method overrides a parent method, the subclass permission must be guaranteed >=the parent permission. 3. When overriding a method, the return value type of the subclass must be <=the return value type of the parent class. 4. When method overrides occur, the exception type thrown by the subclass is <=the exception type thrown by the parent class.

Careless classmates look at the blackboard, look here [Note: only access permissions are >=, return values, exception types are <=]

Here is an example of modifying permissions:

4. On construction methods after inheritance

To give you a better experience, first I'll write a program

   class liGang4 {
        // The parameterless construction method of the parent class.
        public liGang4(){
            System.out.println("The parent construction method executed.");
        }
    }
    class LiXiaoGang4 extends liGang4 {
        // A parameterless construction method for a subclass.
       public LiXiaoGang4(){
           System.out.println("Subclass construction method executed====");
       }
    }
    public class ConstructionDemo {
        public static void main(String[] args) {
            // Create Subclass Object
            LiXiaoGang4 z = new LiXiaoGang4();

        }
    }

Guess what the result is in one minute, and then look at the following:

The parent construction method executed.
Subclass construction method performed ===

Well, after looking at the results, you might be confused.How did the parent constructor method execute?Let's start with analysis, by first instantiating the subclass object in the main method, and then executing the default constructor initialization for the subclass, at which point super() is added by default in the construction method in the <font color=red>first sentence of code </font>; yes, he exists as an open-pending object and does not write!Some tunes~read four "jumps"~Pi's classmates will say, you say there exists, you have no proof~Ah, you bloody handsome kid~as follows: The name of the constructor is the same as the class name, so the subclass cannot inherit the parent constructor.The constructor initializes member variables.Therefore, during the initialization of the subclass, the initialization of the parent class must be performed first.By default, super() is added to the <font color=red>first sentence of code </font> to indicate that the parent class's construction method is called, and the parent class member variable is initialized before it can be used by the child class.

Of course, I have emphasized that many times super() does not write and exists by default, but only in the first sentence of code, not in the first sentence of code, the answer is of course not, this will compile failure, as follows:

5. Examples of polymorphism support for inheritance

Go directly to the code

class A{
    public String show(C obj) {
        return ("A and C");
    }

    public String show(A obj) {
        return ("A and A");
    }

}
class B extends A{
    public String show(B obj) {
        return ("B and B");
    }
}
class C extends B{
    public String show(A obj) {
        return ("A and B");
    }
}
public class Demo1 {
    public static void main(String[] args) {
        A a=new A();
        B b=new B();
        C c=new C();
        System.out.println("Topic 1 " + a.show(a));
        System.out.println("Question 2 " + a.show(b));
        System.out.println("Question 3 " + a.show(c));
    }
}
//Run result:
        //Question 1 A and A
        //Question 2 A and A
        //Question 3 A and C

Actually, both the first and the third questions are easy to understand. The second one is a bit interesting. You will find that there is no parameter of type B in class A. At this time, you should know that subclass inheritance is the parent. In other words, subclass inheritance is the parent naturally. For example, Chinese people must be human, but people are not necessarily Chinese (maybe Mars or African), so <font CoLor=red>The parent class is used as the parameter type. It is possible to pass in the parameters of the subclass directly </font>. Conversely, when the subclass is used as the parameter type and the parameters of the parent class are passed in, a cast is required.

6. Usage of super and this

Before understanding their usage, it must be clear that <font color=red>parent space takes precedence over child object generation </font>

Each time a subclass object is created, the parent space is initialized before its subclass object itself is created.The purpose is that if a child class object contains its corresponding parent space, it can contain members of its parent class, and if the parent member is not private ly modifiable, the child class is free to use the parent member.The code is reflected in the fact that when a construction method of a subclass is called, the construction method of the parent class must be called first.Understanding illustrations are as follows:

5.1, super, and this mean:

super: The storage space identity representing the parent class (which can be interpreted as a reference by the father).

<p>&nbsp;</p>

this: A reference representing the current object (whoever invokes it represents whoever).

5.2, super, and this access members

This. Member Variables --- of this class super.member variable parent's This.member method name () - - of this class super.member method name () - - parent's

5.3, super, and this access construction methods

this(...) - - The construction method of this class Construction Method of super(...) - - Parent Class

Can 5.4, super() and this() be used together?

Can not be used at the same time, this and super cannot appear in a constructor at the same time, because this must call other constructors, and other constructors must also have super statements, so having the same statement in the same constructor will lose the meaning of the statement, and the compiler will not pass.

5.5. Summarize super and this

Each construction method of the subclass has a default super(), which calls the empty parameter construction of the parent class.Manual calls to parent class constructs override the default super().Both super () and this() must be on the first line of the construction method, so they cannot occur together.

Here, java inherits your get to click, get to click, feel free to ~click a compliment~

Recommend reading the next java article in this column

Understanding the Up-Down Transition of Polymorphism Begins with "Mom wants to eat roasted yam"

Welcome to pay attention to my public number, discuss technology, yearn for technology, and pursue technology together...

Tags: Programming Java

Posted on Fri, 08 Nov 2019 16:53:20 -0800 by optimus