Junior — Middle
Can you explain what static typing is compared to duck typing?
sobes.tech AI
Answer from AI
Static typing is when variable types are defined and checked at compile time. For example, in Java or C++, the variable type is fixed and type errors are detected before the program runs.
Duck typing is a dynamic approach common in Python, where the importance is not on an object belonging to a specific type, but on the presence of necessary methods and properties. If an object "behaves like a duck" (has the required methods), it is considered suitable.
Example of duck typing in Python:
def quack(duck):
duck.quack()
class Duck:
def quack(self):
print("Quack")
class Person:
def quack(self):
print("I can quack like a duck")
quack(Duck()) # Quack
quack(Person()) # I can quack like a duck
Here, it is important that the object has a quack() method, not its type.