java inheritance and polymorphism

Inheritance and Polymorphism in Java

Current Status
Not Enrolled
Price
$3.99
Get Started

Inheritance

Inheritance is one of the most important concepts of object-oriented programming. It makes it possible to divide complex problem areas into meaningful class hierarchies. Properties and capabilities that several classes possess are implemented only once in a superclass and inherited by one or more subclasses.

This way, not only is code reused, but the logic of these properties and capabilities can be changed for all inheriting classes in a single place without having to change the code of each individual inheriting class.

Each class can only inherit from one other class in Java. Multiple inheritance is not possible! Other programming languages such as C++ or Python support the concept of multiple inheritance.

The inheriting classes are called superclasses or parent classes, while the inheriting classes are respectively called subclasses or child classes. The inheriting class extends the class from which it inherits, as it (usually) has properties and capabilities beyond those of the superclass.

Polymorphism

Methods can be subject to what is called polymorphism. Polymorphism is Greek and means multiformity. In Java, polymorphism occurs, for example, when two classes use the same method name, but the implementation of the methods differs.

Polymorphism is often used in inheritance, i.e. a variable can be assigned not only objects of the type of the class specified in the declaration, but also objects of the type of the child classes. This only works because each child class must also implement all methods and attributes of its parent classes.  This ensures that all child classes have the same methods as the parent class. However, the methods can be implemented differently, this is called “overwriting” the method.