Overwriting code in Drupal allows customizing existing functionality without directly modifying core files. This can be done by altering hooks, extending classes, or overriding routes and services. In Drupal 7, menu items can be overwritten by hook_menu_alter(), views plugins with hook_views_plugins_alter(), and handlers by altering the file registry with hook_registry_files_alter(). In Drupal 8, menu items are altered by modifying routing files, and views plugins and handlers can be customized via alter hooks or changing the cache_views_info table. Overwriting should aim to extend rather than directly copy core code due to upgrade issues.