DEV Community

Saurabh Chavan
Saurabh Chavan

Posted on

Day 10 : 100DaysOfSwift🚀

Day 10
Classes and inheritance

Similar to constants, variables and functions the user can define class properties and methods

Classes are similar to structs in that they allow you to create new types with properties and methods, but they have five important differences

Creating your own classes

The first difference between classes and structs is that classes never come with a memberwise initializer. This means if you have properties in your class, you must always create your own initializer.

class FullName {
    var firstName: String
    var lastName: String

    init(firstName: String, lastName: String) {
        self.firstName = firstName
        self.lastName = lastName
    }
}

let FName = FullName(firstName: "Saurabh", lastName: "Chavan")
print(FName.firstName)
//Saurabh
Enter fullscreen mode Exit fullscreen mode

Class inheritance

Inheritance allows us to create a new class from an existing class.

The new class that is created is known as subclass (child or derived class) and the existing class from which the child class is derived is known as superclass (parent or base class).

we use the colon : to inherit a class from another class.

Syntax:

// define a superclass
class Animal {
  // properties and methods definition
}

// inheritance
class Dog: Animal {

  // properties and methods of Animal
  // properties and methods of Dog
}
Enter fullscreen mode Exit fullscreen mode

Here, we are inheriting the Dog subclass from the Animal superclass.

Example:

class Animal {

  // properties and method of the parent class
  var name: String = ""

  func eat() {
    print("I can eat")
  }
}

// inherit from Animal
class Dog: Animal {

  // new method in subclass
  func display() {

    // access name property of superclass
    print("My name is ", name);
  }
}

// create an object of the subclass
var labrador = Dog()

// access superclass property and method 
labrador.name = "Rohu"
labrador.eat()

// call subclass method 
labrador.display()

**Output**

I can eat
My name is Rohu
Enter fullscreen mode Exit fullscreen mode

Example 2:

class Sau {
    var name:String = ""
}

class Saurabh:Sau {
    func display(){
        print("My name is",name)
    }
}

let FName = Saurabh()
FName.name = "Saurabh"
FName.display()
//output
My name is Saurabh
Enter fullscreen mode Exit fullscreen mode

Overriding methods

Child classes can replace parent methods with their own implementations – a process known as overriding.

if the same method is defined in both the superclass and the subclass, then the method of the subclass class overrides the method of the superclass. This is known as overriding.

Syntax:

class Vehicle {

  func displayInfo(){
    ... 
  }
}

class Car: Vehicle {

  // override method
  override func displayInfo() {
    ... 
  }   
} 
Enter fullscreen mode Exit fullscreen mode

Top comments (0)