Getting Started With Inherit Keyword in F# Console Application

Introduction

This article explains the use of the inherit keyword in inheritance using  F# console application, the features of "inherit" and how the inherit keywod works in F#.

Use of "inherit" Keyword In Inheritance

Whenever we define a class for information we can create the object of that class to call the function. This is because we define the class. Apart from that the class is supposed to be reuseable and extendable. That is not possible using  structures in C. Inheritance means it is the default association of the base class in derived classes or an object of a base class is embedded in a derived class so that we do not need to create an object of the base class to explicitly call the functions of the base class because the object of the base class is by default embedded in the derived class, that is one of the important features of inheritance.

Features of "inherit"

  • Supports Reuseability of code.
  • Supports Encapsulation (wrap the code).
  • Supports Extendability of code (overrinding the code).

Inheritance is supported by th F# keyword "inherit".

"inherit" Keyword

The inherit keyword identifies that a derived class inherits from a base class.

Syntax: type DerivedClass() =inherit BaseClass()

How to use "inherit" keyoword in inheritance

open System

type BaseClass(val1) =

   member this.val1 = val1

 

type DerivedClass(val1, val2) =

   inherit BaseClass(val1)

   member this.val2 = val2

 

Let's use the following to execute the F# console application.

Step 1:

 Open Visual Studio 2012 then select "New Project" --> "Visual F#" --> "F# Console Application" then click the "Ok" button.

selectapplication.jpg

Step 2:

Write the code in the F# Console Application editor window.

open System

type BaseClass(val1) =

   member this.val1 = val1

 type DerivedClass(val1, val2) =

   inherit BaseClass(val1)

   member this.val2 = val2

let derivedobj = new DerivedClass(10,15)

printfn "Value1=%O" derivedobj.val1

printfn "Value2=%O" derivedobj.val2

System.Console.ReadKey(true)

In the preceding section I have made a one base class and derived class. For example:

type BaseClass(val1) =member this.val1 = val1

and this operator points to the current instance val1 and the derived class uses the inherit keyword that allows access to the properties and fields of the base class. When we create the new instance of the Derived class, for example let derivedobj. derivedobj instance can inherit BaseClass(val1), contains both classes to inherit from and its constructor. In addition at the same time the constructor of the base class must be called.

Step 3:

Debug the program by pressing (F5) to execute the code in the command prompt.

Output

Output.jpg

Summary

This article has exlained the use of the inherit keyword in F# console applications.

Up Next
    Ebook Download
    View all
    Learn
    View all