Virtual types are a way to inject different dependencies into existing classes without affecting other classes.
In simple term we can say creating a sub-class for an existing class.
The following codebase is inserted to the catalog module di.xml to create a virtual type in Magento 2.
<MAGENTO INSTALL DIRECTORY>/vendor/magento/module-catalog/etc/di.xml
Lines 195-199
<virtualType name="Magento\Catalog\Model\Session\Storage" type="Magento\Framework\Session\Storage"> <arguments> <argument name="namespace" xsi:type="string">catalog</argument> </arguments> </virtualType>
Above codebase creates a virtual type for Magento\Catalog\Model\Session\Storage
which alters the namespace of Magento\Framework\Session\Storage
class.
Remember there is no PHP class Magento\Catalog\Model\Session\Storage
in Magento core folder.
Virtual Types are in essence new PHP classes (but actually they are not, they are just links), that extend upon their original class while overriding the original class its constructor arguments by adding those in the di.xml
file.