Java_Inheritance and Polymorphism

Article directory

  • Preface
  • inherit
    • inheritance syntax
    • Inheritance summary
    • super specifies access to the parent
    • Subclass constructor
    • super and this
    • Let’s talk about initialization (execution sequence) again
    • protected keyword
    • Inheritance method
    • final keyword
    • Inheritance and composition
  • Polymorphism
    • Dynamic binding and static binding
    • Polymorphic implementation conditions
    • rewrite

Foreword

Suitable for review

Inheritance

Inheritance syntax

Modifier class subclass extends parent class {<!-- -->
// ...
}

The subclass will inherit the member variables or member methods in the parent class to the subclass.

After the subclass inherits the parent class, it must add its own unique members to reflect the difference from the base class, otherwise there is no need to inherit.

Inheritance summary

In a subclass method or when accessing a member through a subclass object:

  1. If the accessed member variable exists in a subclass, access your own member variable first.
  1. If the member variable being accessed does not exist in the subclass, it will be accessed inherited from the parent class. If the parent class is not defined, a compilation error will be reported.
  1. If the member variable being accessed has the same name as the member variable in the parent class, then access your own first

Member variable access follows the principle of proximity. If you have one, you have priority. If not, look for it in the parent class

When accessing member methods of the parent class in a subclass:

  1. When accessing a method with a different name in the parent class and the subclass through a subclass object, first look for it in the subclass and access it if found. Otherwise, look for it in the parent class and access it if found. Otherwise, a compilation error will be reported.
  1. When accessing a method with the same name of the parent class and the subclass through a derived class object, if the parameter list of the method with the same name of the parent class and the subclass is different (overloading), the calling method depends on the passed parameters. Method access, if not, an error will be reported

super specifies access to the parent

Java provides the super keyword, which is mainly used to access members of the parent class in subclass methods.

Note

  1. Can only be used in non-static methods
  2. In the subclass method, access the member variables and methods of the parent class

Subclass construction method

Father and son, father and son, there is father first and then son, that is: when constructing a subclass object, you need to call the base class constructor first, and then execute the subclass constructor.

In the subclass construction method, no code about the base class construction is written, but when constructing the subclass object, the base class construction method is executed first, and then the subclass construction method is executed, because: the members of the subclass object are It consists of two parts, the part inherited from the base class and the part newly added by the subclass. Father and son must have father first and then son, so when constructing a subclass object, you must first call the construction method of the base class to complete the construction of the members inherited from the base class, and then call the subclass’s own construction method to complete the construction of the members inherited from the base class. The newly added members of the subclass are initialized completely.

Note:

  1. If the parent class explicitly defines a parameterless or default constructor, there will be an implicit super() call by default in the first line of the subclass constructor, that is, calling the base class constructor.
    manufacturing method
  2. If the parent class constructor has parameters, the user needs to explicitly define the constructor for the subclass and select the appropriate constructor in the subclass constructor.
    The parent class constructor method is called, otherwise the compilation fails.
  3. In the subclass constructor, when super(…) calls the parent class constructor, it must be the first statement in the subclass constructor.
  4. super(…) can only appear once in the subclass constructor, and cannot appear at the same time as this (Constructor methods this() and super() must both be on the first line, so they cannot appear at the same time)

super and this

[Similarities]

  1. They are all keywords in Java
  2. Can only be used in non-static methods of a class to access non-static member methods and fields
  3. When called in a constructor, it must be the first statement in the constructor and cannot exist at the same time.

[Differences]

  1. this is a reference to the current object, which is the object that calls the instance method. Super is equivalent to the component of the subclass object inherited from the parent class.
    citations from members
  2. In non-static member methods, this is used to access the methods and properties of this class, and super is used to access the methods and properties inherited from the parent class.
  3. In the constructor method: this(…) is used to call the constructor of this class, super(…) is used to call the constructor of the parent class, and the two calls cannot be used in the constructor at the same time.
    Appears in method
  4. There must be a call to super(…) in the construction method. If the user does not write it, the compiler will increase it, but this(…) will not increase if the user does not write it.

Let’s talk about initialization (execution sequence)

1. The static code block of the parent class takes precedence over the static code block of the subclass and is executed earliest.
2. The parent class instance code block and the parent class construction method are executed immediately.
3. The instance code block and subclass construction method of the subclass are executed immediately.
4. When the subclass object is instantiated for the second time, the static code blocks of the parent class and the subclass will no longer be executed.

Code blocks defined using the static keyword are generally used to initialize static member properties; Static code blockNo matter how many objects are generated, it will only be executed once and is the first to be executed; then In-place initialization and ordinary (instance) code block initialization depend on the order in which they are written. The one written earlier is executed first; then the constructor method is initialized.

protected keyword

A subclass is a derived class (subclass) of the base class (parent class)

Protected modified can be called subclasses in different packages that inherit the class of the package

Note: Although the private member variables in the parent class cannot be directly accessed in the subclass, they are also inherited into the subclass.

When should I use which one?
We hope that classes should be as “encapsulated” as possible, that is, they should hide internal implementation details and only expose necessary information to the callers of the class.
Therefore, we should try to use stricter access permissions when using it. For example, if a method can be private, try not to use public.

In addition, there is a simple and crude method: set all fields as private and all methods as public. However, this method is
Regarding the abuse of access rights, I still hope that students can think carefully when writing code, “who” uses the field methods provided by the class (whether it is used by the class itself, by the caller of the class, or by subclasses)

Inheritance method

Java only supports the following inheritance methods:

Note: Multiple inheritance is not supported in Java.

Always keep in mind that the classes we write are abstractions of real things. The projects we actually encounter in the company are often more complex and may involve a series of complex concepts, all of which require us to use code to represent them, so we really There will also be many classes written in the project. The relationship between classes will also be more complex.

But even so, we don’t want the inheritance hierarchy between classes to be too complicated. Generally, we don’t want more than three levels of inheritance relationships. If there are too many inheritance levels, we need to consider refactoring the code.
If you want to restrict inheritance grammatically, you can use the final keyword

final keyword

The final key can be used to modify variables, member methods, and classes.

  1. Modify variables or fields to represent constants (that is, they cannot be modified)
final int a = 10;
a = 20; // Compilation error
  1. Modified class: indicates that this class cannot be inherited
final public class Animal {<!-- -->
...
}
public class Cat extends Animal {<!-- -->
...
}
// Compilation error
//Error:(3, 27) java: Cannot inherit from final com.bit.Animal

The String class we usually use is modified with final and cannot be inherited.

  1. Modified method: indicates that the method cannot be overridden

Inheritance and composition

Similar to inheritance, composition is also a way to express the relationship between classes, and can also achieve the effect of code reuse. Combination does not involve special syntax
(keywords such as extends), simply make an instance of one class a field of another class.

Inheritance represents an is-a relationship between objects, for example: a dog is an animal and a cat is an animal.

Combination represents a has-a relationship between objects. For example, the relationship between a car and its tires, engine, steering wheel, vehicle system, etc. should be a combination, because the car is composed of these parts.

class Student2 {<!-- -->

}
class Teacher {<!-- -->

}

class School {<!-- -->

    public Student2[] student2s = new Student2[10];
    public Teacher[] teachers = new Teacher[5];
    //You can use "parent class" without inheritance

}

Note Both combination and inheritance can achieve code reuse. Should you use inheritance or combination, you need to choose according to the application scenario. General advice: use combination as much as possible.

Polymorphism

Dynamic binding and static binding

The essence of polymorphism is to use dynamic binding, and different objects have different execution effects.

dynamic binding
(Assume that there is a parent class and a subclass, both of which have the same eat method except for the content)
Create a reference A of the parent class type, let A point to the subclass (new subclass), and then use A to call the eat method
When compiling, it is thought that the eat method of the parent class is still called, but when running, it is bound to the subclass

static binding
When compiling, it has been determined which method to call.
(For example, there is a constructor A without parameters and a constructor B with parameters in the class. When calling the constructor, if the constructor has parameters, constructor B will be executed, and if there are no parameters, constructor A will be executed.)

Polymorphic implementation conditions

To achieve polymorphism in Java, the following conditions must be met, all of which are indispensable:

  1. Must be under the inheritance system
  2. Subclasses must override methods in the parent class
  3. Calling an overridden method through a reference to the parent class

Polymorphic manifestation: When the code is running, when objects of different classes are passed, methods in the corresponding classes will be called

father:

class Animal {<!-- -->
    private String name;
    public void setName(String name) {<!-- -->
        this.name = name;
    }
    public String getName() {<!-- -->
        return this.name;
    }
    public void eat() {<!-- -->
        System.out.println("eat");
    }
}

Two subcategories:

class Cat extends Animal {<!-- -->
    Cat(String name) {<!-- -->
        super.setName(name);
    }
    @Override//Rewrite the eat of the parent class
    public void eat() {<!-- -->
        System.out.println(super.getName() + "Eat cat food");
    }
}
class Dog extends Animal {<!-- -->
    Dog(String name) {<!-- -->
        super.setName(name);
    }
    @Override//Rewrite the eat of the parent class
    public void eat() {<!-- -->
        System.out.println(super.getName() + "Eat dog food");
    }
}

test:

class test {<!-- -->
    public static void main(String[] args) {<!-- -->
        Animal animal = new Cat("cat");//Upward transformation, passing the subclass to the type of the parent class
        animal.eat();

        animal = new Dog("狗子");
        animal.eat();
        //Print as:
        //Cats eat cat food
        //Dogs eat dog food
    }
}

Rewrite

Override: Also called overwriting. Rewriting is when the subclass rewrites the implementation process of the parent class’s non-static, non-private modification, non-final modification, non-constructor method, etc., neither the return value nor the formal parameters can be changed strong>. That is, the shell remains unchanged and the core is rewritten! The advantage of overriding is that subclasses can define their own behavior as needed. That is to say, the subclass can implement the methods of the parent class as needed.

Method overriding rules:

  1. When a subclass overrides a parent class method, it must generally be consistent with the parent class method prototype: The return value type and method name (parameter list) must be completely consistent
  2. The return value type of the overridden method can be different, but the (return type) must have a parent-child relationship
  3. Access permissions cannot be lower than the access permissions of overridden methods in the parent class. For example: If the parent class method is modified by public, the method should be overridden in the subclass
    method cannot be declared as protected
  4. The parent class’s methods modified by static and private and constructor methodscannot be overridden.
  5. Overridden methods can be explicitly specified using the @Override annotation. This annotation can help us perform some legality checks. For example, if the method name is accidentally spelled incorrectly (eat is written as aet, for example), then the compiler will You will find that there is no aet method in the parent class, and a compilation error will be reported, indicating that it cannot
    constitute a rewrite