Method Overloading and Method Overriding.

 


In Swift, method overloading and overriding are two different concepts used to define methods in a class.

Method overloading, also known as "polymorphism," is the ability for a class to have multiple methods with the same name but different parameters. When a method is called, the correct version of the method is chosen based on the number and types of arguments passed to the method.

For example, you can have two methods with the same name calculate but with different parameters:



Method overriding, on the other hand, is the ability for a subclass to provide a new implementation for a method that is already defined in its superclass. The subclass can override the method by providing a new implementation with the same method signature.

For example, you can have a base class Vehicle with a method drive() and a subclass Car that overrides this method to provide a new implementation:


It's important to note that when you override a method, you must use the override keyword before the method declaration to indicate that the method is intended to override a method in the superclass. Also, the overridden method should have the same signature (name, return type and parameters) as the method in the superclass.





Comments

Popular posts from this blog

Object-oriented programming (OOP) in Swift.

Swift Interview Questions and Answers Part 2

Swift Interview Questions and Answers Part 1.