Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Override function

Tags:

ios

swift

I am taking a iOS course online provided by a famous university. I don't understand why the following code use override and it is legal.

  1. According to the official definition, we use override to override superclass' methods. Where is the subclass and superclass in the following code?

  2. What's been override and by what?

public override var description: String {
    return "\(url.absoluteString) (aspect ratio = \(aspectRatio))"
}
like image 406
Jill Clover Avatar asked Aug 26 '16 17:08

Jill Clover


People also ask

What is function overriding with example?

Example 1: C++ Function Overriding So, when we call print() from the Derived object derived1 , the print() from Derived is executed by overriding the function in Base . Working of function overriding in C++ As we can see, the function was overridden because we called the function from an object of the Derived class.

What is override in programming?

In any object-oriented programming language, Overriding is a feature that allows a subclass or child class to provide a specific implementation of a method that is already provided by one of its super-classes or parent classes.

What does it mean to override a function in C++?

Function overriding in C++ is a feature that allows us to use a function in the child class that is already present in its parent class. The child class inherits all the data members, and the member functions present in the parent class.

Why function overriding is used?

Now, when the derived class defines a function that is already defined in the base class, it is called function overriding in C++. Function overriding allows us to perform the specific implementation of a function already used in the base class. Let's understand how function overriding occurs in C++.


1 Answers

Here is an example:

Your original class:

class Person {
    func walk() {
        //do something
    }
}

Your subclass:

class Runner: Person {
    override func walk() {
        //do something that is different from Person's walk
    }
}

In the Runner class, there is an override with the function walk. That is because it is a subclass of Person, and it can override Person's walk function. So If you instantiate a Runner:

var usainBolt = Runner()

And you call the walk function:

usainBolt.walk()

Then that will call the overriden function that you wrote in the Runner class. If you don't override it, it will call the walk function that you wrote in Person.

like image 94
Pranav Wadhwa Avatar answered Oct 18 '22 18:10

Pranav Wadhwa