Inheritance is a form of Abstraction which allows Classes to inherit another parent class’s Methods and Attributes, in order to create a generalised class that other, specialised class can inherit from. The name comes from passing down genetics, (‘inheriting’ genes).
In inheritance, the parent class that passes down it’s methods/attributes is called the superclass, while the child class that inherits from the superclass is called the subclass.
Warning Information Hiding in Inheritance
Not every method or attribute is passed down to subclasses. Generally, most languages have certain visibility modifiers that prevent methods/attributes from being inherited. Java, for example, only allows
public
orprotected
methods/attributes to be inherited
Inheritance defines an “is a” relationship, which is different from Composition, which defines an “has a”:
- A subclass is a superclass
- A
Car
is aVehicle
(hereCar
is the subclass, whileVehicle
is the superclass)
Types
Single Inheritance
Where one subclass inherits from one superclass. This is rarely found, as hierarchical inheritance is usually much more common.
Multiple Inheritance
Where a subclass can inherit from more than one superclass, and all inherited methods and attributes are combined.
Java does not support multiple inheritance, but Python and C++ do.
Hierarchical Inheritance
Where a superclass has multiple subclasses. This is usually the most common form of inheritance, and really is the entire reason we do it in the first place.
Multilevel Inheritance
As the name suggests, multiple levels of inheritance.
Upcasting & Downcasting
Typecasting subclasses to super classes and vice versa is referred to as upcasting and downcasting
Similar to how boxing & unboxing converts a primitive to a wrapper class (and vice versa), upcasting and downcasting allows a sub class to be treated as a superclass, and vice versa.
For example, in Java:
//Assume Animal is the superclass, with Tiger being a subclass
//Upcasting with implicit type conversion
//Tiger is converted to Animal
Animal anim = new Tiger();
//Downcasting with implicit type conversion
//Not possible, returns compile-time Error
Tiger tiger = new Animal(); //ERROR
//Downcasting with explicit type conversion
Animal anim2 = new Animal();
Tiger tiger = (Tiger) anim2;
Uses for this are :#todo