Original public account: “Bigsai” in addition to the public account refused to arbitrarily reprint the article is also included in the carriage return class

Course of learning

In the Java class, all teachers have to mention Object Oriented, and when talking about Object Oriented, they have to mention three characteristics of Object Oriented: encapsulation, inheritance, polymorphism. These three characteristics are closely related but distinct, and this course will take you through Java inheritance.

You may not know exactly what inheritance is for, but you’ve probably had the experience of writing a Java project/assignment that created a lot of similar classes with many of the same methods, did a lot of repetitive work, and felt bloated. The rational use of inheritance can greatly reduce the duplication of code and improve the code reuse.

First acquaintance by inheritance

To learn inheritance, we must first understand what inheritance is and its role from a broad concept, and then learn the specific implementation details of inheritance from a detailed aspect. This chapter is to take you to quickly understand and understand the important concept of inheritance.

What is inheritance

Inheritance is a concept in object-oriented software technology. It makes it easy to reuse old code, greatly reducing development cycles and costs.

Java language is a very typical object-oriented language. Inheritance in Java language means that the subclass inherits the attributes and methods of the parent class, making the subclass object (instance) have the attributes and methods of the parent class, or the subclass inherits methods from the parent class, making the subclass have the same methods as the parent class. Parent classes are sometimes called base classes or superclasses; Subclasses are also sometimes called derived classes.

We know that there are many kinds of animals, which is a big concept. Among animal species, we are familiar with animals such as Cat and Dog. They both have the general characteristics of animals (such as being able to eat and make sounds), but they are different in details (different animals eat differently and have different sounds). When you implement classes like Cat and Dog in the Java language, you need to inherit from Animal. After inheritance, specific Animal classes such as Cat and Dog are subclasses, and Animal class is the parent class.

Why inheritance is needed

You might ask why inheritance? When it comes to implementation, we can create Dog, Cat and other classes and implement their specific methods. Implementing this inheritance seems to make the structure of the class less clear.

If there are only two or three classes, and each class has very limited properties and methods, there is no need to implement inheritance, but this is not the case. In fact, there are often many classes in a system with many similarities, such as cats and dogs being animals, or students and teachers being humans. Each class may have many of the same properties and methods, so that if every class is rewritten not only the code will be messy, but the code will also be a lot of work.

At this point, the advantages of inheritance come out: you can directly use the attributes and methods of the parent class, you can also have your own new attributes and methods to meet the expansion, and the method of the parent class can be rewritten if you need to change. Using inheritance in this way not only greatly reduces the amount of code, but also makes the structure of the code more visible.

So from a code level we designed the complete Animal class like this:

class Animal
{
    public int id;
    public String name;
    public int age;
    public int weight;

    public Animal(int id, String name, int age, int weight) {
        this.id = id;
        this.name = name;
        this.age = age;
        this.weight = weight;
    }
    // Omit the get set method here
    public void sayHello(a)
    {
        System.out.println("hello");
    }
    public void eat(a)
    {
        System.out.println("I'm eating");
    }
    public void sing(a)
    {
        System.out.println("sing"); }}Copy the code

The Dog, Cat, and Chicken classes can be designed like this:

class Dog extends Animal/ / inheritanceanimal
{
    public Dog(int id, String name, int age, int weight) {
        super(id, name, age, weight);// Call the parent constructor}}class Cat extends Animal{

    public Cat(int id, String name, int age, int weight) {
        super(id, name, age, weight);// Call the parent constructor}}class Chicken extends Animal{

    public Chicken(int id, String name, int age, int weight) {
        super(id, name, age, weight);// Call the parent constructor
    }
    / / chickens lay eggs
    public void layEggs(a)
    {
        System.out.println("I am an old hen laying eggs, clack, clack, clack! Clack, clack!"); }}Copy the code

Classes that inherit from Animal can directly use Animal properties and methods without having to write them repeatedly, and classes that have their own methods can be easily extended. In the code above you need to note that extends is used to implement inheritance.

Inherited classification

Inheritance is divided into single inheritance and multiple inheritance. The Java language only supports single inheritance of classes, but the purpose of multiple inheritance can be achieved by implementing interfaces. Let’s outline the differences with a table and then expand on them.

define The advantages and disadvantages
Single inheritance

A subclass has only one parent class Advantages: Relatively clear in class hierarchy

Disadvantages: The richness of the structure is sometimes insufficient for use
Multiple inheritance (Java does not support multiple inheritance, but you can use multiple inheritance in other ways)

A subclass has multiple direct parent classes Advantages: High degree of subclass richness

Disadvantages: Prone to confusion

Single inheritance

Single inheritance is when a subclass has only one parent, like the Animal class and its subclass we talked about above. Single inheritance is relatively clear in the class hierarchy, but the disadvantage is that the structure is sometimes not rich enough for use.

Multiple inheritance (Not supported by Java, but possible)

Multiple inheritance is when a subclass has more than one direct parent class. The advantage of this is that the subclass has all the characteristics of its parent class, and the subclass is very rich, but the disadvantage is that it can be messy. Below is an example of confusion.

Although Java does not support multiple inheritance, there are three ways to achieve the effect of multiple inheritance in Java: inner classes, multi-level inheritance, and implementation interfaces.

The inner class can inherit a class unrelated to the outer class, which ensures the independence of the inner class. Based on this, the effect of multiple inheritance can be achieved.

Multi-level inheritance: A subclass inherits from a parent class. If the parent class also inherits from other classes, this is called multi-level inheritance. The subclass then owns all the attributes and methods of the inherited class.

Implementing interfaces is undoubtedly the best way to meet the needs of multiple inheritance. A class can implement multiple interfaces to meet its own needs in rich and complex environments. A class is an entity with attributes and methods, as opposed to an interface, which tends to be a set of methods. For example, take douluo mainland Tang Three, his existing inheritance relationship may be like this:

How to implement inheritance

Implementation inheritance can be implemented using the implements keyword in addition to the extends used above. Now, let me explain them to you one by one.

The extends keyword

In Java, class inheritance is single inheritance, meaning that a subclass can only have one parent, so extends can only inherit one class. Its usage syntax is:

classA subclass ofextendsThe parent class name{}
Copy the code

For example, the Dog class inherits from Animal, which looks like this:

class Animal{} // Define Animal class
class Dog extends Animal{} //Dog descends from Animal
Copy the code

When a subclass inherits its parent class, it has the non-private properties and methods of the parent class. Animal sayHello() = sayHello() = sayHello() = sayHello() = sayHello() = sayHello() The specific code is:

class Animal {
    public void  sayHello(a)// Method of the parent class
    {
        System.out.println("hello,everybody"); }}class Dog extends Animal/ / inheritanceanimal
{}public class test {
    public static void main(String[] args) {
       Dog dog=newDog(); dog.sayHello(); }}Copy the code

When hit Run, the Dog subclass can use the Animal parent’s methods directly.

The implements keyword

Using the implements keyword enables Java to have the property of multiple inheritance. In the case of interfaces implemented by classes, a class can implement multiple interfaces (separated by commas). A Java interface is a declaration of a series of methods; there is no concrete implementation of a method in an interface. When a subclass implements an interface, it must override methods in the interface.

DoA: sayHello(); eat() : eat(); Cat2: doA: eat(); And the sayHello() and eat() methods need to be overridden in the class. The specific code is:

interface doA{
     void sayHello(a);
}
interface doB{
     void eat(a);
    // The following error is reported: methods in the interface cannot be specified, but can only be declared
    //public void eat(){System.out.println("eating"); }
}
class Cat2 implements  doA.doB{
    @Override// The methods in the interface must be overridden
    public void sayHello(a) {
        System.out.println("hello!");
    }
    @Override
    public void eat(a) {
        System.out.println("I'm eating"); }}public class test2 {
    public static void main(String[] args) {
        Cat2 cat=newCat2(); cat.sayHello(); cat.eat(); }}Copy the code

When the Cat class implements the doA and doB interfaces, it needs to implement the declared methods.

Characteristics of inheritance

The main content of inheritance is that a subclass inherits its parent class and overwrites its methods. When you use a property or method of a subclass, you first create an object, and the object is created through a constructor. In the constructor, you may call some properties and methods of the subclass, so you need to know the this and super keywords in advance. After the object is created, the override method is called and the difference between override and overload is distinguished. So this section explains this, super keyword – > constructor – > method overrides – > method overloading.

The this and super keywords

This and super keywords are very important knowledge points in inheritance. They represent the reference of the current object and the reference of the parent object respectively. They are very similar but have some differences.

This represents the current object and is a reference to itself.

This. Attribute // calls a member variable, distinguishing it from a local variable.() // calls a method of the classCopy the code

Super represents a superclass object and is a reference to the superclass.

The super. Attribute // represents the member variable super in the superclass object. Method () // represents the method defined in the superclass object super() // represents the call to the superclass constructorCopy the code

In addition, the this and super keywords can only appear in code that is not static.

Both this() and super() can only appear on the first line of a constructor. If this() is used to call another constructor of the current class, and super() is used to call a constructor of the parent class, the two can only choose one based on their usage needs.

Create class D1 and subclass D2 as follows:

class D1{
    public D1(a) {}// No arguments
    public void sayHello(a) {
        System.out.println("hello"); }}class D2 extends D1{
    public String name;
    public D2(a){
        super(a);// Call the parent constructor
        this.name="BigSai";// Assign a value to the current class member variable
    }
    @Override
    public void sayHello(a) {
        System.out.println("Hello, I am."+this.name);
    }
    public void test(a)
    {
        super.sayHello();// Call the parent method
        this.sayHello();// Call other methods of the current class}}public class test8 {
    public static void main(String[] args) {
        D2 d2=newD2(); d2.test(); }}Copy the code

The results are as follows:

A constructor

A constructor is a special kind of method that has the same name as a class. Object creation is accomplished through the constructor, whose main function is to complete the initialization of the object. However, constructor is a special method in inheritance (such as cannot inherit), so understand and learn the rules and requirements of constructor in inheritance.

Constructors can be divided into parameterized constructors and parameterless constructors, which can be set appropriately according to their own usage requirements. But there are a few things to note about the constructor in inheritance:

The constructor of the parent class cannot be inherited:

Because the constructor syntax has the same name as the class, inheritance does not change the method name, and if a subclass inherits the constructor from its parent class, it clearly conflicts with the constructor syntax. For example, if the Father constructor is Father(), then the Father constructor is Father(). If the Father constructor is Father(), then the Father constructor is Father(), and the Son constructor is Father(), then the Father constructor is Father().

The constructor of a subclass must call the constructor of its parent class:

The Java virtual machine constructs a superclass object before creating a subclass object, and then constructs subclass-specific properties after the superclass object is constructed, which is called memory overlay. The Java virtual machine’s superclass object executes the superclass constructor, so the subclass constructor must call super(), the superclass constructor. For example, a simple inheritance case would read:

class A{
    public String name;
    public A(a) {// No arguments
    }
    public A (String name){// There are parameters}}class B extends A{
    public B(a) {// No arguments
       super(a); }public B(String name) {// There are parameters
      //super();
       super(name); }}Copy the code

If the parent constructor is not explicitly called in a subclass constructor, the constructor with no arguments in the parent class is called by default.

If you don’t use super() when you inherit from a subclass, the program will still be fine. In order to save code, the system will automatically add the parent class with no arguments. If you don’t believe me, we will modify the above class slightly:

Method Override

Method rewriting is the occurrence of methods (including return value types, method names, and argument lists) in a subclass identical to those in the parent class, based on inheritance. You can think of it as the method shell stays the same, but the core content is rewritten.

Here’s an easy-to-understand way to rewrite the case:

class E1{
    public void doA(int a){
        System.out.println("This is the method of the superclass."); }}class E2 extends E1{
    @Override
    public void doA(int a) {
        System.out.println("I'm overriding the superclass method, this is the subclass method."); }}Copy the code

The @override annotation declares that the method is an annotation method, which can help you check the syntax of the overridden method. Of course, it is ok if it is not added, but it is recommended.

For rewriting, you need to note the following:

From the requirements of rewriting:

  • Override the same method as the parent (return value type, method name, argument list)
  • Method overrides exist only between subclasses and superclasses, and can only be overridden within the same class

In terms of access permissions:

  • A subclass method cannot narrow the access rights of a parent method
  • A subclass method cannot throw more exceptions than a parent method
  • A private method of a parent class cannot be overridden by a subclass

Static and non-static:

  • A static method of a parent class cannot be overridden by a subclass as a nonstatic method
  • A subclass may define a static method of the same name as a static method of the parent class in order to hide the static method of the parent class in the subclass (meeting the override constraint)
  • A nonstatic method of a parent class cannot be overridden by a subclass as a static method

In terms of abstract and non-abstract:

  • Abstract methods of a parent class can be overridden by subclasses in two ways (i.e., implementation and override)
  • A nonabstract method of a parent class can be rewritten as an abstract method

Of course, these rules may involve some modifiers, which are covered in detail in the third level.

Method Overload

If you have two methods with the same method name but different parameters, you can say that one method is an overload of the other. Method overloading rules are as follows:

  • Overloaded methods must change the argument list (different number or type or order of arguments)
  • Overloaded methods can change the return type
  • Overloaded methods can change access modifiers
  • Overloaded methods can declare new or broader check exceptions
  • Methods can be overridden in the same class or in a subclass
  • Overloaded functions cannot be distinguished by return value types

Overloading can generally be understood as having the same method name to do the same thing, but with different argument lists and other conditions. An example of a simple method overload is the add() method of class E3.

class E3{
    public int add(int a,int b){
        return a+b;
    }
    public double add(double a,double b) {
        return a+b;
    }
    public int add(int a,int b,int c) {
        returna+b+c; }}Copy the code

Method overwriting differs from method overloading:

Method overrides and method overrides can be confusing in name but differ in content. Here is a table listing the differences:

The mark Methods to rewrite Method overloading
On the structure Vertical structure is a relationship between parent and child classes Horizontal structure is a kind of homogeneous relationship
The list of parameters Cannot be modified You can modify
Access modifier The subclass’s access modifier range must be greater than or equal to the parent class’s access modifier range You can modify
An exception is thrown A subclass method exception must be either a parent method exception or a child of a parent method exception You can modify

Inheritance and modifiers

Java modifiers role is to modify or limit, class or a class member each modifier has its own role, and there may be some special modifiers in succession make modified properties or methods cannot be inherited, or inheritance need some other conditions, the following is described in detail in succession some function and feature of the modifier.

The Java language provides many modifiers that define classes, methods, or variables, usually at the beginning of a statement. It is mainly divided into the following two categories:

  • Access modifier
  • Non-access modifier

Access modifiers: public, protected, default, and private. Non-access modifiers Static, final, and Abstract modifiers are introduced here.

Access modifier

Public, protected, default(no modifiers), private modifiers are very important in object orientation, and you need to know the rules for using modifiers in inheritance.

First, we all know that the scope of different keywords is different. The scope of the four keywords is as follows:

The same class The same package Different types of steamed buns Different packages are not subclasses
private
default
protect
public
  1. Private: The narrowest modifier in the Java language that restricts access, generally referred to as “private.” Properties and methods decorated by them can only be accessed by objects of that class, not subclasses, and not across packages.

  2. Default :(also called friendly) it does not add any access modifiers and is usually called “default access” or “package access”. In this mode, access is allowed only in the same package.

  3. Protected: An access modifier between public and private, commonly called “protected access.” Properties and methods decorated by them can only be accessed by methods and subclasses of the class itself, even if the subclasses are accessible in different packages.

  4. Public: The widest access-restricted modifier in the Java language, commonly called “public.” The classes, properties, and methods it decorates can be accessed not only across classes, but also across packages.

When a Java subclass overrides an inherited method, it cannot reduce the access of the method. The access modifier of the subclass cannot be smaller than that of the parent class, which is more open. If the parent class is protected, the subclass can only be protected or public. It must not be default(the default access range) or private. So methods that need to be overridden in inheritance cannot be decorated with private modifiers.

If it’s not clear, you can see it in a couple of small cases, where you write an A1 class that implements four methods with four modifiers, subclass A2 inherits A1, and when you override A1 you can see that private methods of the parent class cannot be overridden, and non-private methods cannot be overridden with modifiers that have a smaller scope (greater than or equal to).

The correct case would be:

class A1 {
    private void doA(a){}void doB(a){}//default
    protected void doC(a){}
    public void doD(a){}}class A2 extends A1{

    @Override
    public void doB(a) {}// Method access modifier permissions overridden by inherited subclasses can be extended

    @Override
    protected void doC(a) {}// An inherited subclass overrides the same access modifier permissions as its parent class

    @Override
    public void doD(a) {}// Do not use protected or default
}
Copy the code

Also note that exceptions thrown by subclasses in inheritance must be exceptions thrown by or children of the exception thrown by the parent class. In the following example, four method tests can find that the exception of a subclass method cannot be greater than the range of exceptions thrown by the corresponding method of the parent class.

The correct case would be:

class B1{
    public void doA(a) throws Exception{}
    public void doB(a) throws Exception{}
    public void doC(a) throws IOException{}
    public void doD(a) throws IOException{}}class B2 extends B1{
    // The exception scope can be the same as the parent class
    @Override
    public void doA(a) throws Exception {}// The exception scope can be smaller than the parent class
    @Override
    public void doB(a) throws IOException {}// The exception scope cannot be larger than the parent scope
    @Override
    public void doC(a) throws IOException {}// Do not throw exceptions larger than IOException
    @Override
    public void doD(a) throws IOException {}}Copy the code

Non-access modifier

Access modifiers are used to control access permissions, but non-access modifiers each have their own role. Static, final, and Abstract modifiers are described below.

The static modifier

Can be used with variables, methods, and classes. Static variables, static methods (also called class variables, class methods) If you use static modifier variables or methods in a class, they can be accessed directly from the class, without creating a class object to access the members.

We’re probably going to use static methods when we’re designing classes, and there are a lot of utility classes like Math and Arrays that have lots of static methods. There are many rules for static modifiers. Here are only the rules for Java inheritance:

  • Constructors are not allowed to be declared static.
  • There is no current object in a static method, so you cannot use this, and of course you cannot use super.
  • Static methods cannot be overridden by non-static methods
  • Static methods can be overridden by static methods

Take a look at the following examples to prove the above rule:

The source code is:

class C1{
    public  int a;
    public C1(a){}
   Public static C1(){} constructor is not allowed to be declared static
    public static void doA(a) {}
    public static void doB(a) {}}class C2 extends C1{
    public static  void doC(a)// Static methods do not have the current object, so you cannot use this and super.
    {
        //System.out.println(super.a);
    }
    public static void doA(a){}Static methods can be overridden by static methods
   // public void doB(){} static methods cannot be overridden by non-static methods
}
Copy the code

Final modifier

Final variables:

  • Once a variable has been assigned, it cannot be reassigned. Instance variables decorated with final must have an explicit initial value (that is, not just a declaration). The final modifier is usually used with the static modifier to create class constants.

The final method:

  • Final methods ina parent class can be inherited by subclasses, but cannot be overridden by subclasses. The main purpose of declaring a final method is to prevent the contents of the method from being modified.

Final class:

  • Final classes cannot be inherited. No class can inherit any of the features of a final class.

So whether a variable, method, or class is modified by final, it means final. The content cannot be modified.

The abstract modifier

Abstract is used to modify classes and methods. It is called abstract class and abstract method.

Abstract methods: There are many methods of different classes that are similar, but the specific content is not quite the same, so we can only extract his declaration, there is no concrete method body, that is, abstract methods can express concepts but not concrete implementation.

Abstract classes: Classes that have abstract methods must be abstract classes that can express concepts but cannot construct entities.

Abstract classes and methods have more content and rules. Here are just a few usage and rules related to inheritance:

  • Abstract classes are also classes. If a class inherits from an abstract class, it cannot inherit from another (class or abstract class).
  • Subclasses can inherit from abstract classes, but must implement all the abstract methods of their parents. If not, subclasses must also be defined as abstract classes
  • A class is complete only if it implements all the abstract methods of its parent class.

For example, we could design an abstract class like People and an abstract method, and do this in a subclass:

abstract class People{
    public abstract void sayHello(a);// Abstract methods
}
class Chinese extends People{
    @Override
    public void sayHello(a) {// Implement abstract methods
        System.out.println("Hello"); }}class Japanese extends People{
    @Override
    public void sayHello(a) {// Implement abstract methods
        System.out.println("Wow, wow, wow."); }}class American extends People{
    @Override
    public void sayHello(a) {// Implement abstract methods
        System.out.println("hello"); }}Copy the code

Object classes and transitions

To mention Java inheritance, you have to mention the root class of all classes: Object(java.lang.object) class. If a class does not explicitly declare its parent (extends xx is not written), then the default parent is Object. Any class can use the methods of Object and create classes that can transition up and down from Object. So the Object class is a necessary knowledge point to grasp and understand inheritance. Java upward and downward transformation in Java is used a lot, but also based on inheritance, so Java transformation is also to master and understand inheritance must be knowledge points.

Description of Object class

  1. Object is the root class of a class hierarchy. All classes implicitly inherit from Object.

  2. All Java objects have the Object default method

  3. The Object class has one constructor, and it has no arguments

Object is the parent of all Java classes, the top of the class inheritance structure, and the most abstract class. Methods like toString(), equals(), hashCode(), wait(), notify(), and getClass() are all methods of Object. You’ll probably see a lot more of them, but more of them are toString() and equals() methods, which we’ll often have to rewrite to fit our usage needs.

The **toString()** method returns the string of the object, which needs to be overridden because the object is constructed differently. Otherwise, the class name @hashCode format is returned by default.

If we override toString() and call toString() directly, we can return our custom output of the class as a string instead of having to manually piece together the output of the string each time, greatly simplifying the output operation.

The **equals() method compares two objects to be equal. Equality doesn’t necessarily have to be the same in address, but sometimes it’s equal in content. For example, the String class overwrites the euqals()** method by comparing the contents of strings.

upcasting

Upward transformation: Instantiating a parent object (large) by subclass object (small range) is an automatic transformation. The logic of the upward transition is best represented by a graph:

When a superclass reference variable points to a subclass object, only the declared methods of the parent class can be used, but the methods of the subclass will be executed if overridden, and the methods of the parent class will be executed if the methods are not overridden.

Downward transition

Downcast: Instantiate a subclass object (small) with a parent object (large), and cast it to the subclass type with parentheses () on writing. However, the parent class reference variable must actually refer to a subclass object in order to succeed in the transformation. Here is also a good illustration of the logic of the upward transformation:

Once a subclass reference variable points to an object (a Son() object) that the parent class refers to, it is transformed down and can call methods that are specific to subclasses but not to the parent class.

Here is a case of upward transition and downward transition:

Object object=new Integer(Awesome!);// Upward transition

Integer i=(Integer)object;Object->Integer

String str=(String)object;// The compiler does not report an error but the runtime does
Copy the code

Initialization order of child and parent classes

In Java inheritance, parent classes are initialized in the following order:

  1. Static member variables and static code blocks in the parent class

  2. Static member variables and static code blocks in subclasses

  3. Ordinary member variables and code blocks in the parent class, constructor of the parent class

  4. Ordinary member variables and code blocks in a subclass, constructor of a subclass

In general, it’s static > non-static, superclass > subclass, non-constructor > constructor. Member variables and code blocks of the same class (for example, normal variables and code blocks) need to be logically executed from front to back.

Static variables, also known as class variables, can be viewed as global variables. Static member variables and static code blocks are initialized when the class is loaded, while non-static variables and code blocks are initialized when the object is created. So static initialization is faster than non-static initialization.

When creating a subclass object, you need to create a superclass object first, so the superclass takes precedence over the subclass.

When the constructor is called, some initialization is done on the member variables, so normal member variables and code blocks are superior to constructor execution.

To further explain this sequence, take a closer look at the JVM execution flow. The following test code is:

class Father{
    public Father(a) {
        System.out.println(++b1+"Parent class constructor");
    }// The parent constructor is fourth
    static int a1=0;// The parent class is static
    static {
        System.out.println(++a1+"The parent class static." ");
    }
    int b1=a1;// The parent member variables and code blocks are third
    {
        System.out.println(++b1+"Parent code block"); }}class Son extends Father{
    public Son(a) {
        System.out.println(++b2+"Subclass Constructor");
    }// Subclass constructor sixth
    static {// Subclass static step 2
        System.out.println(++a1+"Static" subclass);
    }
    int b2=b1;// Subclass member variables and code blocks fifth
    {
        System.out.println(++b2 + "Subclass code block"); }}public class test9 {
    public static void main(String[] args) {
        Son son=newSon(); }}Copy the code

Execution Result:

conclusion

Well, that’s it for inheritance, one of the three main features of Java object-oriented inheritance – you’ve got it. Consider Java’s three main object-oriented features: encapsulation, inheritance, and polymorphism. Finally, can you get a general idea of their characteristics?

Encapsulation: it is the encapsulation of the class. Encapsulation is the encapsulation of the attributes and methods of the class. It only exposes the methods but not the details of the specific use.

Inheritance: A subclass inherits its parent class. A subclass has all the attributes and methods of its parent class, except for the private attributes and methods of its parent class, and can extend its own attributes and methods based on this. The main purpose is to reuse code.

Polymorphism: Polymorphism is the ability to have many different manifestations or forms of the same behavior. That is, a parent class may have several subclasses, and each subclass implements a variety of methods of the parent class. When calling the parent class method, the parent class references variables pointing to different instances of the child class and executes different methods. This is called the parent class method is polymorphic.

Finally, I’ll give you a picture to help you understand the relationship.

Original is not easy, Bigsai would like to ask digg friends to help with two things:

  1. One key three even support, you are sure to be my creative power in nuggets.

  2. Wechat search “bigsai”, follow my official account (original dry goods blogger), not only free ebook for you, I will be the first time to share knowledge and technology in the official account. Can also pull you into force button punch group punch together LeetCode.

  3. Recently, I have been arranging the articles about solving problems and digging gold into e-books, which will be released free of charge for everyone at the first time.