|
Subtyping and Inheritance Before discussing this example, however, it is necessary to discuss the difference between subtyping and inheritance, since the former term applies but not the latter. Subtyping is a concept that deals with relationships between types. Types can have subtypes, and subtypes can be the basis for subsequent derived types. A subtype is an abbreviation for a base type. This can be illustrated using the example of vehicles. Suppose we define a type called. Objects of this type represent all vehicles. Then we define a subtype called.
Only passenger cars will have this type. Whenever an object of type is used, it can be replaced by another object of subtype. The Liskov substitution principle here means that after replacing the object, the system will run as expected. The inheritance mechanism involves using existing code from a base photo retouching class in a subclass. This is a way to pass fields and methods to another class. Since subtyping is accomplished through inheritance, these issues are highly interrelated, and the differences between them can be difficult to understand. Example Suppose we are creating an application that performs some operations on geometric shapes.

In the first version of the program, the type is defined, which represents a rectangle: At some point in the application, we have a function that calculates the area of a rectangle: Using such code might look like this: In this case, The function will return the result. After a while, it was necessary to introduce a new figure, the square. We know that mathematically a square is a rectangle. Therefore, it seems like a good idea to extend the class as follows: Since the width and height of the square are equal, the methods of the base class have been overridden and setting any parameter will also change the other parameter.
|
|