Skip to main content

Swift Inheritance

Utilizing the properties of one class to another class is called inheritance. Inheritance is provide an interface to access parent class properties to child class. Parent class also known as super class and base class. And child class also known as derived class and sub-class. Inheritance is useful technique for add new features to existing class and also possible to override existing methods. There are syntax as follows.

class Base{
  //data members
  //member functions
}
class Derived:Base{
  //data members
  //member functions
}

Note that in declaration of derived class , Using of colon and base class name is represented as inheritance. For example.

class Accessory{

  var warranty:String
  var rating:Int=3
  
  init(_ warranty:String){
    self.warranty=warranty
  }
}
class Computer:Accessory{
  
  var generation:String
  init(_ generation:String,_ warranty:String){
   self.generation=generation
   super.init(warranty) //set superclass properties
  }
}
let obj=Computer("5'th","Three Year")
//Accessing Instance variables
print("Warranty : \(obj.warranty)")
print("Rating : \(obj.rating)")
print("Generation : \(obj.generation) Generation")
Inheritance Example In Swift

Output

Warranty : Three Year
Rating : 3
Generation : 5'th Generation

In this example Computer is derived class which are inherited the properties of Accessory class. help of Derived class object there can be access the properties of Base class. There are used class object and dot operator to access the class properties.

Observe that in above program base class are have a constructor, and inside a derived class constructor can be initialize base class constructor properties by using of supper.init().





Comment

Please share your knowledge to improve code and content standard. Also submit your doubts, and test case. We improve by your feedback. We will try to resolve your query as soon as possible.

New Comment