Consider the following Swift classes. What will be printed when Child().greet() is called?
class Parent { func greet() { print("Hello from Parent") } } class Child: Parent { override func greet() { super.greet() print("Hello from Child") } } Child().greet()
Remember that super.greet() calls the parent class method first.
The Child class overrides greet() and calls super.greet() first, which prints "Hello from Parent". Then it prints "Hello from Child".
super in Swift class methods?Which of the following best explains why you would call super.method() inside an overridden method?
Think about how inheritance works and extending behavior.
Calling super.method() lets the child class reuse the parent class's code and then add or change behavior.
Examine this Swift code snippet. What error will it produce?
class Parent { init() { print("Parent init") } } class Child: Parent { override init() { print(self) super.init() } }
Swift requires calling super.init() before using self in initializers.
In Swift, you must call super.init() before accessing self or its properties in an initializer. Printing before calling super.init() accesses self, causing an error.
Which of the following is the correct way to call a parent class method named display() inside an overridden method?
Remember the Swift syntax for calling parent methods.
In Swift, super.methodName() calls the parent class's method. Other options are invalid syntax.
count after calling increment() twice?Given these Swift classes, what is the value of count after Child().increment() is called twice?
class Parent { var count = 0 func increment() { count += 1 } } class Child: Parent { override func increment() { super.increment() count += 2 } } let obj = Child() obj.increment() obj.increment() print(obj.count)
Each call adds 1 from super.increment() and 2 more in Child.increment().
Each increment() call adds 3 to count (1 from parent, 2 from child). Two calls add 6 total.