define

If for every object o1 of type T1 there is an object O2 of type T2, such that the behavior of all programs P defined by T1 does not change when all objects o1 are substituted for O2, then type T2 is a subtype of type T1.

In plain English, a subclass can extend the functionality of its parent class, but cannot change the functionality of its parent class.

inheritance

advantages

1) Code sharing reduces the workload of creating classes, and each subclass has the attributes and methods of its parent class;

2) Improve code reuse;

3) A subclass may resemble but differ from its parent;

4) Improve the extensibility of code;

5) Improve the openness of products or projects.

disadvantages

1) Inheritance is intrusive. Whenever you inherit, you must have the attributes and methods of the parent class.

2) Reduce code flexibility. Subclasses have more constraints on their parent class. Enhanced coupling.

3) When the parent class constants, variables, methods are modified, need to consider the changes of the child class.

Examples of Inheritance disadvantages

The wooden fish is not a fish and can’t swim

Design a fish

Public class Fish {public void swim() {system.out.println (" Fish can swim "); }}Copy the code

call

public class Client { public static void main(String[] args) { Fish fish = new Fish(); fish.swim(); }}Copy the code

The results of

Design a wood fish successor fish

Wooden fish can’t swim and can knock

Public class WoodenFish extends Fish {public void swim() {system.out.println (" WoodenFish can't swim "); } public void knock() {system.out.println (system.out.println); }}Copy the code

call

public class Client { public static void main(String[] args) { WoodenFish fish = new WoodenFish(); fish.swim(); fish.knock(); }}Copy the code

The results of

What we found was that the fish, which was functioning normally, was not able to swim properly. The reason is that the method of the parent class was rewritten when the method was given the same name. As a result, all the codes of the function of fish swimming were called by the rewritten method of the method of fish swimming, resulting in the error of the normal function.

Four meanings

  • A subclass can implement an abstract method of the parent class, but cannot override a nonabstract method of the parent class.

  • Subclasses can add their own special methods.

  • When a subclass’s method overrides a parent class’s method, the method’s preconditions (that is, the method’s parameters) are looser than the parent method’s input parameters.

  • When a subclass’s method implements an abstract method of the parent class, the method’s postcondition (that is, the method’s return value) is stricter than the parent class’s.