Junior — Middle
Explain the concept of polymorphism in object-oriented programming and how it is applied in development practice.
sobes.tech AI
Answer from AI
Polymorphism is a principle of object-oriented programming that allows objects of different classes to be processed through a single interface. This means that the same method can behave differently depending on the object that calls it.
In iOS development practice (for example, in Swift), polymorphism is often implemented through inheritance and protocols. For instance, you can define a base class or protocol with a method, and then create subclasses or structures that implement this method in their own way.
Example in Swift:
protocol Drawable {
func draw()
}
class Circle: Drawable {
func draw() {
print("Drawing a circle")
}
}
class Square: Drawable {
func draw() {
print("Drawing a square")
}
}
func render(shape: Drawable) {
shape.draw() // calls the draw method on any object implementing Drawable
}
let circle = Circle()
let square = Square()
render(shape: circle) // Drawing a circle
render(shape: square) // Drawing a square
This approach simplifies extensibility and code maintenance, allowing for more versatile functions and classes.