3
Abstract: inheritance is a concept in object-oriented software technology. It makes it easy to reuse the previous code, can greatly shorten the development cycle, and reduce the development cost.

This article is shared from HUAWEI CLOUD community " "4D Graphic" The most aunt-level Java inheritance detailed explanation in the history丨【Run! JAVA】 ", original author: bigsai.

Course Guide

In the Java class, all teachers have to mention object-oriented (Object Oriented), and when talking about object-oriented, they have to mention three major characteristics of object-oriented: encapsulation, inherits , polymorphism. The three characteristics are closely related but have differences. This course will take you to learn Java inheritance.

You may not know what is the use of inheritance, but you have a high probability of having this experience: when writing a Java project/homework, you create a lot of similar classes, there are many same methods in the class, and you have done a lot of repetitive work. Very bloated. The reasonable use of inheritance can greatly reduce repetitive code, improves code reusability.
image.png

Inherited first acquaintance

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

What is inheritance

Inheritance (English: inheritance) is a concept in object-oriented software technology. It makes it easy to reuse the previous code, which can greatly shorten the development cycle and reduce development costs.

The Java language is a very typical object-oriented language. In the Java language, inheritance means that the subclass inherits the properties and methods of the parent class, so that the subclass object (instance) has the properties and methods of the parent class, or the subclass inherits from the parent class. Method, so that the child class has the same method as the parent class . Parent classes are sometimes called base classes and super classes; subclasses are sometimes called derived classes.

Let's take an example: We know that there are many kinds of animals, which is a relatively large concept. Among the types of animals, we are familiar with cats, dogs and other animals. They all have the general characteristics of animals (such as being able to eat and making sounds), but they are different in details (different animals). The food is different, the cry is different). When implementing classes such as Cat and Dog in the Java language, you need to inherit the Animal class. After inheritance, specific animal classes such as Cat and Dog are subclasses, and the Animal class is the parent class.
image.png

Why do you need inheritance

You may wonder why inheritance is needed? In the specific implementation, when we create the Dog, Cat and other classes, it is enough to implement the specific methods. The realization of this inheritance seems to make the structure of this class not so clear.

If there are only two or three classes, there is really no need to implement inheritance when the properties and methods of each class are very limited, but this is not the case. In fact, there are often many classes in a system with many similarities, such as cats. It is the same animal as the dog, or the student and teacher are the same person. Each class may have a lot of the same properties and methods. In this case, if each class is rewritten, not only the code will be messy, but the code workload will also be huge.

At this time, the advantages of inheritance come out: you can directly use the properties and methods of the parent class, you can also have your own new properties and methods to meet the expansion, and the methods of the parent class can be rewritten if you need to change it. This use of inheritance not only greatly reduces the amount of code, but also makes the code structure more clearly visible.
image.png

So from the code level, we design this 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;
    }
    //这里省略get set方法
    public void sayHello()
    {
        System.out.println("hello");
    }
    public void eat()
    {
        System.out.println("I'm eating");
    }
    public void sing()
    {
        System.out.println("sing");
    }
}

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

class Dog extends Animal//继承animal
{
    public Dog(int id, String name, int age, int weight) {
        super(id, name, age, weight);//调用父类构造方法
    }
}
class Cat extends Animal{

    public Cat(int id, String name, int age, int weight) {
        super(id, name, age, weight);//调用父类构造方法
    }
}
class Chicken extends Animal{

    public Chicken(int id, String name, int age, int weight) {
        super(id, name, age, weight);//调用父类构造方法
    }
    //鸡下蛋
    public void layEggs()
    {
        System.out.println("我是老母鸡下蛋啦,咯哒咯!咯哒咯!");
    }
}

After the respective classes inherit Animal, they can directly use the properties and methods of the Animal class without rewriting. Each class can be easily expanded if it has its own methods. In the above code, 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 use a table to outline the difference between the two first, and then expand the explanation.
image.png

Single inheritance

Single inheritance means that a subclass has only one parent class, such as the Animal class and its subclasses we mentioned above. Single inheritance is relatively clear in the class hierarchy, but the disadvantage is that the richness of the structure sometimes cannot meet the needs of use.

Multiple inheritance (Java does not support, but can be achieved)

Multiple inheritance means that a subclass has multiple direct parent classes. The advantage of this is that the subclass has all the characteristics of the parent class, and the richness of the subclass is very high, but the disadvantage is that it is easy to cause confusion. The picture below shows a confusing example.
image.png

Although Java does not support multiple inheritance, Java has three ways to achieve the effect of multiple inheritance, which are internal classes, multi-layer inheritance, and implementation interfaces.

inner class can inherit a class that has nothing to do with the outer class, ensuring the independence of the inner class. It is based on this that the effect of multiple inheritance can be achieved.

multi-layer inheritance: the child class inherits the parent class, if the parent class also inherits other classes, then this is called multi-layer inheritance . In this way, the subclass will have all the attributes and methods of the inherited class.
image.png

realizes interface 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. Comparing a class with an interface, the class is an entity with attributes and methods, while the interface prefers a set of methods . For example, take Tang San from Douluo Mainland, his inheritance relationship may be like this:
image.png

How to implement inheritance

Inheritance addition extends outside used above , you can also use the keyword implements to achieve. Below, let me explain to you one by one.

extends keyword

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

class subclass name extends parent class name{}
For example, the Dog class inherits the Animal class, and it looks like this:

class Animal{} //定义Animal类
class Dog extends Animal{} //Dog类继承Animal类

After the child class inherits the parent class, it has the non-private properties and methods of the parent class. If you don’t understand, please take a look at this case. Create a project under IDEA, create a test class for testing, create Animal and Dog classes respectively, and write a sayHello() method for Animal as the parent class. After the Dog class inherits the Animal class, you can Call the sayHello() method. The specific code is:

class Animal {
    public void  sayHello()//父类的方法
    {
        System.out.println("hello,everybody");
    }
}
class Dog extends Animal//继承animal
{ }
public class test {
    public static void main(String[] args) {
       Dog dog=new Dog();
       dog.sayHello();
    }
}

When you click to run, the Dog subclass can directly use the methods of the Animal parent class.
image.png

implements keyword

Using the implements keyword can make Java have multiple inheritance characteristics in disguise. The scope of use is the case where a class implements an interface. A class can implement multiple interfaces (the interface and the interface are separated by a comma). A Java interface is a declaration of a series of methods, There is no specific implementation of methods in an interface . When a subclass implements an interface, it must override the methods in the interface.

Let's take a look at a case, create a test2 class for testing, create doA interface and doB interface respectively, doA interface declares sayHello() method, doB interface declares eat() method, create Cat2 class to implement doA and doB interfaces, and in the class Need to rewrite sayHello() method and eat() method. The specific code is:

interface doA{
     void sayHello();
}
interface doB{
     void eat();
    //以下会报错 接口中的方法不能具体定义只能声明
    //public void eat(){System.out.println("eating");}
}
class Cat2 implements  doA,doB{
    @Override//必须重写接口内的方法
    public void sayHello() {
        System.out.println("hello!");
    }
    @Override
    public void eat() {
        System.out.println("I'm eating");
    }
}
public class test2 {
    public static void main(String[] args) {
        Cat2 cat=new Cat2();
        cat.sayHello();
        cat.eat();
    }
}

When the Cat class implements the doA and doB interfaces, it needs to implement its declared methods. Click to run the result as follows. This is a simple case of a class implementing an interface:
image.png

Inherited characteristics

The main content of inheritance is that the child class inherits the parent class and overrides the method of the parent class. When using the properties or methods of the subclass, you must first create an object, and the object is created by the construction method . In the construction method, we may call some properties and methods of the subclass, so we need to master this and super keyword. After creating this object, call the method of rewriting the parent class, and distinguish the difference between rewriting and overloading. Therefore, this section will explain in the order of this and super keywords—>constructor—>method rewriting—>method overloading.

this and super keywords

this and super keywords are inherited in very important knowledge , respectively, and references cited parent object of the current object, the two are very similar there are some differences.

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

this.属性 // 调用成员变量,要区别成员变量和局部变量
this.() // 调用本类的某个方法
this() // 表示调用本类构造方法

super represents the parent class object and is a reference to the parent class.

super.属性 // 表示父类对象中的成员变量
super.方法() // 表示父类对象中定义的方法
super() // 表示调用父类构造方法

In addition, the this and super keywords can only appear in non-static modified code.

Both this() and super() can only appear in the first line of the construction method. If you use this() to call other construction methods of the current class, use super() to call a construction method of the parent class, so both You can only choose one according to your own needs.

Write a small case, create D1 class and subclass D2 as follows:

class D1{
    public D1() {}//无参构造
    public void sayHello() {
        System.out.println("hello");
    }
}
class D2 extends D1{
    public String name;
    public D2(){
        super();//调用父类构造方法
        this.name="BigSai";//给当前类成员变量赋值
    }
    @Override
    public void sayHello() {
        System.out.println("hello,我是"+this.name);
    }
    public void test()
    {
        super.sayHello();//调用父类方法
        this.sayHello();//调用当前类其他方法
    }
}
public class test8 {
    public static void main(String[] args) {
        D2 d2=new D2();
        d2.test();
    }
}

The result of the execution is:
image.png

Construction method

The construction method is a special method, it is a method with the same name as the class . The creation of the object is completed by the construction method, and its main function is to complete the initialization of the object. However, the construction method in inheritance is a special method (for example, it cannot be inherited), so it is necessary to understand and learn the rules and requirements of the construction method in inheritance.

The construction method can be divided into parameter construction and non-parameter construction. This can be set up according to your own needs. But the construction method in inheritance has the following points to pay attention to:

parent class cannot be inherited:

Because the construction method syntax is the same name as the class, and inheritance does not change the method name. If the subclass inherits the construction method of the parent class, it obviously conflicts with the construction method syntax. For example, the construction method of the Father class is named Father(). If the Son class inherits the Father() construction method of the Father class, it will be defined with the construction method: the construction method and the class have the same name, so the parent class cannot be inherited in the subclass Construction method, but the subclass will call the construction method of the parent class.

subclass must call the construction method of its parent class:

Java virtual machine constructs the parent class object before constructing the subclass object, and then constructs the subclass-specific attributes after the superclass object is constructed. This is called memory overlay . The Java virtual machine constructs the parent class object to execute the parent class's construction method, so the sub-class construction method must call super(), which is the parent class's construction method. For example, a simple inheritance case should be written like this:

class A{
    public String name;
    public A() {//无参构造
    }
    public A (String name){//有参构造
    }
}
class B extends A{
    public B() {//无参构造
       super();
    }
    public B(String name) {//有参构造
      //super();
       super(name);
    }
}

If the construction method of the subclass does not explicitly call the construction method of the parent class, the system defaults to call the construction method of the parent class without parameters.

Sometimes when you write inheritance, the subclass does not use the super() call, and the program is still okay. In fact, this is to save code. The system will automatically add the parent class's no-parameter construction method when it is executed. If you don’t believe it, we are right. The above class is slightly modified and executed:
image.png

Method override (Override)

Method overriding means that the same method (including return value type, method name, parameter list) appears in the subclass and in the parent class, and it is based on inheritance. You can understand that the shell of the method remains unchanged, but the core content is rewritten.

Here is a simple and easy-to-understand method rewriting case:

class E1{
    public void doA(int a){
        System.out.println("这是父类的方法");
    }
}
class E2 extends E1{
    @Override
    public void doA(int a) {
        System.out.println("我重写父类方法,这是子类的方法");
    }
}

The @Override annotation shows that the method is declared as an annotation method, which can help you check the grammatical correctness of the overriding method. Of course, it is okay if you don't add it, but it is recommended to add it.

For rewriting, you need to pay attention to the following points:

From the rewrite requirements:

  • The overridden method should be consistent with the parent class (including return value type, method name, parameter list)
  • Method rewriting only exists between the subclass and the parent class, and can only be overloaded in the same class

From the perspective of access rights:

  • The subclass method cannot narrow the access rights of the parent class method
  • Subclass methods cannot throw more exceptions than parent methods
  • The private method of the parent class cannot be overridden by the subclass

From the static and non-static point of view:

  • The static method of the parent class cannot be rewritten as a non-static method by the subclass
  • The subclass can be defined in the static method of the parent class with the same name, so that the static method of the parent class can be hidden in the subclass (satisfying the overriding constraint)
  • Non-static methods of the parent class cannot be rewritten as static methods by the subclass

From the abstract and non-abstract point of view:

  • The abstract method of the parent class can be rewritten by the subclass in two ways (ie, implementation and rewriting)
  • Non-abstract methods of the parent class can be rewritten as abstract methods

Of course, these rules may involve some modifiers, which will be introduced in detail in the third level.

Method overload (Overload)

If there are two methods with the method name , but the parameters are inconsistent, then it can be said that one method is an overload of the other method. The method overloading rules are as follows:

  • The overloaded method must change the parameter list (the number or type or order of the parameters is not the same)
  • The overloaded method can change the return type
  • The overloaded method can change the access modifier
  • Overloaded methods can declare new or broader checked exceptions
  • Methods can be overloaded in the same class or in a subclass
  • The return value type cannot be used as the criterion for distinguishing overloaded functions

Overloading can usually be understood as the same method name to accomplish the same thing, but the parameter list is different and other conditions may also be different. A simple example of method overloading, the add() method in class E3 is an overloaded method.

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) {
        return a+b+c;
    }
}

The difference between method rewriting and method overloading:

Method overriding and method overloading are easy to confuse in name, but there is a big difference in content. The following table lists the differences:
image.png

Inheritance and modification

The role of Java modifiers is to modify or restrict classes or class members. Each modifier has its own role, and there may be special modifiers in inheritance that make the modified properties or methods not inherited, or inheritance requires some For other conditions, the functions and characteristics of some modifiers in inheritance are described in detail below.

The Java language provides many modifiers. Modifiers are used to define classes, methods or variables, and are usually placed at the forefront of statements. Mainly divided into the following two categories:

  • Access modifier
  • Non-access modifier

The access modifiers here mainly explain four access control modifiers: public, protected, default, and private. Non-access modifiers Here are the static modifiers, final modifiers and abstract modifiers.

Access modifier

public, protected, default (no modifier), private modifier is a very important knowledge point in object-oriented, and you also need to understand the rules of using various modifiers in inheritance.

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

  1. private: The narrowest modifier in the Java language that restricts access rights, generally called "private". The attributes and methods modified by it can only be accessed by objects of this class, and its subclasses cannot be accessed, let alone cross-package access.
  2. default: (also called friendly) that is, without any access modifiers, usually called "default access permissions" or "package access permissions". In this mode, only access in the same package is allowed.
  3. protected: An access modifier between public and private, generally referred to as "protected access rights". The attributes and methods modified by it can only be accessed by the methods and subclasses of the class itself, even if the subclasses are in different packages.
  4. public: The modifier with the widest access restriction in the Java language, generally referred to as "public". The modified classes, attributes, and methods can not only be accessed across classes, but also across packages.

When a Java subclass overrides inherited methods, cannot reduce the access rights of the method. The access modifier scope of the subclass inherited from the parent class cannot be smaller than the parent class , which is more open. If the parent class is protected, Its subclass can only be protected or public, and must not be default (the default access range) or private. Therefore, methods that need to be rewritten in inheritance cannot be modified with private modifiers.

If you are still not quite clear, you can easily understand it by looking at a few small cases. Write a class A1 with four modifiers to implement four methods, use subclass A2 to inherit A1, and rewrite A1 method, you will find the parent class Private methods cannot be rewritten, and the scope of modifiers used in non-private method rewriting cannot be reduced (greater than or equal to).
image.png

The correct case should be:

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

    @Override
    public void doB() { }//继承子类重写的方法访问修饰符权限可扩大

    @Override
    protected void doC() { }//继承子类重写的方法访问修饰符权限可和父类一致

    @Override
    public void doD() { }//不可用protected或者default修饰
}

Also note that the inheritance must be the exception thrown by the parent class or the child exception thrown by the parent class. In the following case, the four method tests can find that the exception of the subclass method cannot be greater than the scope of the exception thrown by the parent class corresponding method.

The correct case should be:

class B1{
    public void doA() throws Exception{}
    public void doB() throws Exception{}
    public void doC() throws IOException{}
    public void doD() throws IOException{}
}
class B2 extends B1{
    //异常范围和父类可以一致
    @Override
    public void doA() throws Exception { }
    //异常范围可以比父类更小
    @Override
    public void doB() throws IOException { }
    //异常范围 不可以比父类范围更大
    @Override
    public void doC() throws IOException { }//不可抛出Exception等比IOException更大的异常
    @Override
    public void doD() throws IOException { }
}

Non-access modifier

Access modifiers are used to control access rights, and non-access modifiers each have their own functions. The static, final, and abstract modifiers are introduced below.

static modifier

Static translates as "static" and can be used with variables, methods and classes. called static variables, and static methods (also called class variables and class methods) are . If you use static to modify variables or methods in a class, they , without creating an object of the class to access the members.

We may use static methods when designing classes. Many tool classes such as Math and Arrays have many static methods written in them. There are many rules for static modifiers, here is only the rules related to Java inheritance usage:

  • The construction method is not allowed to be declared as static.
  • There is no current object in a static method, so this cannot be used, and of course super cannot be used.
  • Static methods cannot be overridden (overridden) by non-static methods
  • Static methods can be overridden (overridden) by static methods

You can see the following cases to prove the above rules:

The source code is:

class C1{
    public  int a;
    public C1(){}
   // public static C1(){}// 构造方法不允许被声明为static
    public static void doA() {}
    public static void doB() {}
}
class C2 extends C1{
    public static  void doC()//静态方法中不存在当前对象,因而不能使用this和super。
    {
        //System.out.println(super.a);
    }
    public static void doA(){}//静态方法能被静态方法重写
   // public void doB(){}//静态方法不能被非静态方法重写
}

final modifier

final variables:

  • Final means "last and final". variable 160f531098cb8f is assigned, it cannot be reassigned to . Instance variables modified by final must be explicitly specified with initial values (that is, they cannot just be declared). The final modifier is usually used together with the static modifier to create class constants.

final method:

  • parent class can be inherited by the subclass, but cannot be overridden by the . The main purpose of declaring a final method is to prevent the content of the method from being modified.

final class:

final class cannot be inherited from , no class can inherit any characteristics of final class.

Therefore, whether variables, methods, or classes are modified by final, they all have the final and final meaning. The content cannot be modified.

abstract modifier

Abstract English name is "abstract", mainly used to modify classes and methods, called abstract classes and abstract methods.

abstract method: has many different types of methods that are similar, but the specific content is not the same, so we can only extract his statement, there is no specific method body, that is, abstract methods can express concepts but cannot be implemented.

abstract class: A class with abstract methods must be an abstract class. The abstract class can express concepts but cannot construct entities.

Abstract classes and abstract methods have more content and rules. Here are only some usages 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 they must implement all the abstract methods of the parent class. If it cannot be fully implemented, then the subclass must also be defined as an abstract class
  • Only by implementing all the abstract methods of the parent class can it be a complete class.

image.png
For example, we can design a People abstract class and an abstract method like this, which is specifically completed in the subclass:

abstract class People{
    public abstract void sayHello();//抽象方法
}
class Chinese extends People{
    @Override
    public void sayHello() {//实现抽象方法
        System.out.println("你好");
    }
}
class Japanese extends People{
    @Override
    public void sayHello() {//实现抽象方法
        System.out.println("口你七哇");
    }
}
class American extends People{
    @Override
    public void sayHello() {//实现抽象方法
        System.out.println("hello");
    }
}

Object class and transformation

When it comes to Java inheritance, I have to mention the root class of all classes: Object (java.lang.Object) class. If a class does not explicitly declare its parent class (that is, extends xx is not written), then the parent of this class is the default The class is the Object class. Any class can use the methods of the Object class, and the created class can also be transformed up and down with the Object. Therefore, the Object class is a necessary knowledge point for mastering and understanding inheritance. The Java up-and-down transformation is used a lot in Java, and it is also based on inheritance. Therefore, Java transformation is also a necessary knowledge point for mastering and understanding inheritance.

Object class overview

  1. Object is the root class of the class hierarchy, and all classes implicitly inherit from the Object class.
  2. All objects in Java have Object default methods
  3. There is one construction method of the Object class, and it is constructed without parameters

Object is the parent class of all classes in Java, the top of the entire class inheritance structure, and the most abstract class. Like toString(), equals(), hashCode(), wait(), notify(), getClass(), etc. are all methods of Object. You may encounter them frequently in the future, but the more common ones are the toString() method and the equals() method. We often need to rewrite these two methods to meet our needs.

toString() The method indicates the string returned to the object. Because the structure of each object is different, it needs to be rewritten. If it is not rewritten, it will return the class name in @hashCode format by default.

If you rewrite the toString() method and directly call the toString() method you can return our customized content output of this type converted into a string type, instead of manually patching it into a string content output every time, greatly Simplify output operations.

*equals() method mainly compares whether two objects are equal, because the equality of objects does not necessarily require the address of the two objects to be the same, and sometimes the content is the same, we will consider it to be equal , such as String class Rewrite the euqals() * method to compare whether the string content is equal.
image.png

Upward transformation

Up-casting: Instantiating the parent-class object (large-scale) through the sub-class object (small-scale), this is an automatic conversion. A picture can well represent the logic of upward transformation:
image.png

After the parent class reference variable points to the child class object, only the methods declared by the parent class can be used, but if the method is overridden, the method of the child class will be executed, and if the method is not overridden, the method of the parent class will be executed.

Downcast

Downcasting: Instantiate subclass objects (small scope) through the parent class object (large range). In writing, the parent class object needs to be forced to be converted to the subclass type by adding parentheses (). However, the actual reference of the parent class reference variable must be a subclass object to be successfully transformed. Here is also a picture that can well represent the logic of the upward transformation:
image.png

After the subclass reference variable points to the object pointed to by the parent class reference variable (a Son() object), the downcast is completed, and some methods specific to the subclass but not available to the parent can be called.

Here is a case of upward transformation and downward transformation:

Object object=new Integer(666);//向上转型

Integer i=(Integer)object;//向下转型Object->Integer,object的实质还是指向Integer

String str=(String)object;//错误的向下转型,虽然编译器不会报错但是运行会报错

Initialization order of child and parent class

In Java inheritance, the order of initialization of parent and child classes is as follows:

  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, the constructor of the parent class
  4. Ordinary member variables and code blocks in the subclass, the constructor of the subclass

In general, it is static>non-static, parent class>child class, non-constructor>constructor . Member variables and code blocks of the same category (such as ordinary variables and ordinary code blocks) are executed from front to back, and logic needs to be paid attention to.

This is not difficult to understand. Static variables are also called class variables, which can be regarded 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 is faster than non-static initialization.

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

When the constructor is called, some initialization operations are performed on the member variables, so ordinary member variables and code blocks are better than the constructor.

As for why this order is deeper, it is necessary to have a deeper understanding of the JVM execution process. The following test code is:

class Father{
    public Father() {
        System.out.println(++b1+"父类构造方法");
    }//父类构造方法 第四
    static int a1=0;//父类static 第一 注意顺序
    static {
        System.out.println(++a1+"父类static");
    }
    int b1=a1;//父类成员变量和代码块 第三
    {
        System.out.println(++b1+"父类代码块");
    }
}
class Son extends Father{
    public Son() {
        System.out.println(++b2+"子类构造方法");
    }//子类构造方法 第六
    static {//子类static第二步
        System.out.println(++a1+"子类static");
    }
    int b2=b1;//子类成员变量和代码块 第五
    {
        System.out.println(++b2 + "子类代码块");
    }
}
public class test9 {
    public static void main(String[] args) {
        Son son=new Son();
    }
}

Results of the:
image.png

Concluding remarks

Okay, this is the end of the introduction of inheritance, one of the three major characteristics of Java object-oriented inheritance-excellent you have already mastered. Let's take a look at the three major characteristics of Java object-oriented: encapsulation, inheritance, and polymorphism. Finally, can you roughly understand their characteristics?

Encapsulation: It is the encapsulation of the class. Encapsulation is the encapsulation of the properties and methods of the class. Only the methods are exposed without exposing the specific usage details. Therefore, when we generally design class member variables, most of them are set to be private and go through some get and set methods. Read and write.

Inheritance: The child class inherits the parent class, that is, "the child inherits the father's business". The child class has all the properties and methods of the parent class except private, and can expand its own new properties and methods on this basis. The main purpose is to reuse code.

Polymorphism: Polymorphism is the ability to have multiple different manifestations or forms of the same behavior. That is to say, a parent class may have several subclasses, and each subclass implements various methods of the parent class. When the parent class method is called, the parent class reference variable points to different subclass instances and executes different methods. This is the so-called parent class method. Stateful.

Finally, I will give you a picture to explore the relationship.
image.png

Click to follow, and get to know the fresh technology of


华为云开发者联盟
1.4k 声望1.8k 粉丝

生于云,长于云,让开发者成为决定性力量