(also inheritance, subclassing, specialization)
Subtyping is a concept in object-oriented programming that refers to the relationship between two classes, where one class is considered a subtype of another. In subtyping, the subclass inherits the properties and behavior of the superclass, which means that the subclass can use all the methods and attributes defined in the superclass. The subclass can also define its own methods and attributes and override the methods inherited from the superclass.
Subtyping is a key feature of object-oriented programming, as it allows for code reuse and abstraction. It enables developers to create complex software systems by building on top of existing code.
Subtyping use cases
- Inheritance. Subtyping is used to create new classes that inherit properties and behavior from existing classes. For example, if you have a class called Animal, you could create a subclass called Cat that inherits properties and behavior from the Animal class.
- Polymorphism. Subtyping enables polymorphism, which allows different objects to be treated as if they are of the same type. This is done by creating multiple subclasses that inherit from the same superclass and implementing a common interface for those subclasses.
- Interface segregation. Subtyping is used to implement interface segregation by creating multiple interfaces, each of which defines a specific set of methods, and then having classes implement only the interfaces that are relevant to them.
- Type checking. Subtyping is used to verify that the types of values and variables are consistent throughout a program. This is achieved by checking that a variable of a subtype can be assigned to a variable of its supertype without causing a type error.
- Generic programming. Subtyping is used to enable generic programming and allow algorithms and data structures to be written in a way that is independent of specific types.