Download as pdf or txt
Download as pdf or txt
You are on page 1of 11

UNIT –III

INHERITANCE
A key feature of OOP is reusability. It's always time saving and useful if we can
reuse something that already exists rather than trying to create the same thing
again and again. Reusing the class that is tested, debugged and used many
times can save us time and effort of developing and testing it again. Once a
class has been written and tested, it can be used by other programs to suit the
program's requirement. This is done by creating a new class from an existing
class.

The process of deriving a new class from an existing class is called


Inheritance. The old class is called the base class and the new class is called
derived class. The derived class inherits some or everything of the base class.
In Visual Basic we use the Inherits keyword to inherit one class from other. .

The general form of deriving a new class from an existing class looks as follows:
<access-specifier> Class <base_class>
...
End Class

Class <derived_class>: Inherits <base_class>


...
End Class

Using Inheritance, we can use the variables, methods, properties, etc, from the
base class and add more functionality to it in the derived class.
Types of Inheritance
 Single Inheritance - Deriving a new class from single base class
 Multilevel Inheritance - Deriving a class from another derived class
 Hierarchical Inheritance - Deriving more than one class from same base
 Multiple Inheritance - Deriving a class from more than one base class.
Not supported directly but in a crude way VB.Net supports multiple
inheritance using interface concept

The following code demonstrates the process of Inheritance in VB.NET


‘Single Inheritance
Module Module1
'Base Class
Class Shape
Protected l, b As Double
Sub ReadShape(ByVal i As Double, ByVal j As Double)
l=i
b=j
End Sub
End Class
'Derived Class
Class Rectangle : Inherits Shape
Sub Area()
Console.WriteLine("Area = " & (l * b))
End Sub
End Class
Sub Main()
Dim r As New Rectangle()
r.ReadShape(10, 20)
r.Area()
Console.ReadKey()
End Sub
End Module

VB.Net introduces the following statements and modifiers to support


inheritance:
 Inherits — Specifies the base class.
 NotInheritable — Prevents programmers from using the class as a base
class.
 MustInherit — Specifies that the class is intended for use as a base
class only. Instances of MustInherit classes cannot be created.
 Overridable — Allows a property or method in a class to be overridden
in a derived class.
 Overrides — Overrides an Overridable property or method defined in the
base class.
 NotOverridable — Prevents a property or method from being overridden
in derived class.
 MustOverride — Requires that a derived class override the property or
method. When the MustOverride keyword is used, the method definition
consists of just the Sub, Function, or Property statement. No other
statements are allowed, and specifically there is no End Sub or End
Function statement. MustOverride methods must be declared in
MustInherit classes.
 MyBase — Refers to the immediate base class and used to call
methods in the base class
 MyClass — Refers to the containing class and its inherited members.

Polymorphism
The ability to take more than one form is known as polymorphism. VB.Net
implements dynamic polymorphism using Virtual Method.

When a virtual method is invoked by a base reference, the method to be called


is determined based on the object's type, not on reference type.
We declare a method as virtual method by specifying the Overridable modifier.
Virtual methods may be redefined in derived class using Overrides modifier.
Overrides keyword instruct the compiler that we are overriding a virtual
method.

Dynamic polymorphism occurs only when we use base reference to point to


derived object

Program using Virtual Methods – Dynamic Polymorphism


Module Module1
Class shape
‘Virtual Methods
Overridable Sub Read(ByVal i As Integer, ByVal j As Integer)
Console.WriteLine("Base Method")
End Sub
Overridable Sub Area()
Console.WriteLine("Base Method")
End Sub
End Class

Class Rectangle : Inherits shape


Private l, b As Integer
Public Overrides Sub Read(ByVal i As Integer, ByVal j As Integer)
l=i
b=j
End Sub
Public Overrides Sub Area()
Console.WriteLine("Area = " & (l * b))
End Sub
End Class

Sub Main()
Dim r As shape
r = New Rectangle()
r.Read(10, 20)
r.Area()

Console.ReadKey()
End Sub
End Module
Abstract Class
Abstract Classes are classes that cannot be instantiated, and are either
partially implemented or not at all implemented. One key difference between
abstract classes and interfaces is that a class may implement any number of
interfaces, but may inherit from only one abstract class.

The Abstract Classes are declared using the keyword MustInherit. The
MustInherit keyword specifies that a class cannot be instantiated and can be
used only as a base class. An abstract class can contain abstract and concrete
methods. When a class is inherited from an abstract class, it must implement
every abstract method defined by the abstract class or must be defined
abstract itself.
Abstract Methods
Abstract methods are overridable methods that are declared with the
MustOverride keyword and provide no implementation. A class that inherits
from a class with abstract methods must provide an implementation for the
abstract methods or must be abstract itself.

Difference between Abstract Method and Virtual Methods


 An Abstract method must be overridden in child classes where as virtual
method is not compulsory to override.
 An abstract method doesn't have implementation detail where as virtual
method has it.
 Only abstract class can have abstract method where as any class can
have virtual method

Example Using Abstract Class and Abstract Methods


‘Abtract Class
MustInherit Class Animal
‘Abstract Method
MustOverride Sub Speaks()
End Class

Class Dog : Inherits Animal


Public Overrides Sub Speaks()
Console.WriteLine("Barks")
End Sub
End Class
Sub Main()
Dim d As New Dog()
d.Speaks()
Console.ReadKey()
End Sub
Sealed Classes
A class that cannot be inherited is called a sealed class. Means you cannot
inherit the sealed classes. In VB.NET a sealed class is represented as Non
Inheritable class as follows
NotInheritable class SealedClass
[Members]
End Sub
A sealed class cannot be used as a base class. For this reason, it cannot also
be an abstract class. Sealed classes are primarily used to prevent derivation.

Example using Sealed Class


'Sealed Class
NotInheritable Class Sample
Sub display()
Console.WriteLine("Welcome")
End Sub
End Class

Class Deri : Inherits Sample 'Error



End Class
If a class is derived from a sealed class then the compiler throws an error.
Interface
Interfaces define the properties, methods, and events that classes can
implement. Interfaces are better suited for applications that require many
possibly unrelated object types to provide certain functionality.
Declaring Interfaces
Interface definitions are enclosed within the Interface and End Interface
statements.
An interface can contains one or more procedures, functions, properties,
interfaces, events and other types but none of them are implemented in the
interface itself. It is the responsibility of the class that implements the interface
to define the code for these members.
Syntax
AccessModifier Interface <InterfaceName>
[Members]
End Interface
Implementing Interfaces
Interfaces can be implemented by classes and structures using Implements
Keyword
The Keyword Implements is used in two ways.
 The Implements statement signifies that a class or structure implements
an interface.
 The Implements keyword signifies that a class member or structure
member implements a specific interface member
Example
Module Module1
Interface i1
Sub m1()
End Interface
Class Sample : Implements i1
Public Sub m1() Implements i1.m1
Console.WriteLine("m1")
End Sub
End Class
Sub Main()
Dim s As New Sample()
s.m1()
End Sub
End Module
Implementing Multiple Inheritance Using Interface
VB.NET supports multiple inheritance using interface concept. A Class can
implement one or more interfaces
Module Module1
Interface i1
Sub m1()
End Interface

Interface i2
Sub m2()
End Interface

Class sample
Implements i1, i2

Public Sub m1() Implements i1.m1


Console.WriteLine("m1")
End Sub

Public Sub m2() Implements i2.m2


Console.WriteLine("m2")
End Sub
End Class

Sub Main()
Dim s As New sample()
s.m1()
s.m2()
End Sub
End Module

Interface Inheritance
An interface can inherit from one or more base interfaces. In the following
example, the interface MyInterface inherits from two base interfaces, Base1
and Base2:
interface MyInterface : Implements Base1, Base2
[Members]
End Interface
Example – Interface Inheritance
Module Module1
Interface i1
Sub m1()
End Interface

Interface i2 : Inherits i1
Sub m2()
End Interface

Class sample
Implements i2

Public Sub m1() Implements i1.m1


Console.WriteLine("m1")
End Sub

Public Sub m2() Implements i2.m2


Console.WriteLine("m2")
End Sub
End Class

Sub Main()
Dim s As New sample()
s.m1()
s.m2()
End Sub
End Module
Namespaces
Namespaces are used to create logical groups of related classes and interfaces.
Need for Namespace
 Namespaces allow us to organize Classes so that they can be easily
accessed in other applications.
 Namespaces enable us to avoid any naming conflicts between classes
that have the same name. We can use two classes with the same name in
an application provided they belong to different namespaces.
Creating Namespaces
Every project in VB.Net has a root namespace, which is set in the Property
page of the project. When we create a project, by default, the name of the root
namespace for the project is set to the name of the new project. For example,
the root namespace for a project named MyApp is MyApp.

We can also organize classes using the Namespace keyword.


For example, we can create a user-defined namespace called College in the
project called MyApp and place the class Student within the College block as
follows

Namespace College
Class Student
[Members]
End Class
End Namespace
The fully qualified or proper usage of the class Student will be
MyApp.College.Student

Using Namespaces
We can use the Namespace either explicitly through direct addressing or
implicitly through the Imports statement.

Direct addressing involves accessing any class by providing the fully qualified
name. For Example
Dim t as New System.Threading.Thread()
Imports Statement allows us to use a class directly without giving fully
qualified name. For Example
Imports System.Threading
….
Dim t as New Thread()
Imports Statement must appear after any Option statements, if present, but
before any other code. It can be applied only to the namespaces. It cannot be
applied to classes directly. The following Imports statement is incorrect
Imports System.Threading.Thread

The scope of import statement is restricted to the source file in which it is


used.
Example
Namespace Perls
Class Website
Public Shared Sub Execute()
Console.WriteLine("Perls Website")
End Sub
End Class
End Namespace
Namespace Ruby
Class Website
Public Shared Sub Open()
Console.WriteLine("Ruby Website")
End Sub
End Class
End Namespace

Imports MyApp.Perls
Module Module1
Sub Main()
'Accessing using Imports
Website.Execute()
'Accessing using fully qualified name
Ruby.Website.Open()
Console.ReadKey()
End Sub
End Module
Components
A component is a special type of executable built from a .NET project. After
compilation the component is typically referenced by applications needing the
services provided by the component. Thus, the components facilitate
reusability, which is one of the important objectives of object oriented
programming.
Creating the Component
The steps in creating a .NET DLL component are as follows
1. Create a new Application using File->New->Project option
2. The New Project dialog appears. Select Class Library Template and
enter Project Name as MyComponent
3. Change the name of the class from Class1 to College
4. Enter the following code
Public Class College
Dim CollegeName, Location As String
Public Sub New(ByVal c As String, ByVal l As String)
CollegeName = c
Location = l
End Sub
Public Sub Display()
Console.WriteLine("College Name - " & CollegeName)
Console.WriteLine("Location - " & Location)
End Sub
End Class
5. Compile this class as a DLL by clicking Build on the Debug menu
The DLL that results from the build command is placed into the \bin\debug
directory immediately below your .NET project directory. By default, the DLL
has the same name as your component project. For instance, if you named the
project MyComponent in the New Project dialog, the DLL produced by your
project will be named MyComponent.dll. This name is also the default
Namespace name for the classes contained within the project.
Using the Component
The steps in creating an application that uses the above component are
1. Create a new application using File->New->Project option
2. The New Project dialog appears. Select Console Application and enter
Project Name as TestApp
3. In the Solution Explorer, click on the project name and select Add
Reference option. Add Reference dialog appears
4. Click the Browse tab and then browse to locate the component DLL built
in the preceding section
5. Select the MyComponent.dll file, click Open, and then click OK.
The Solution Explorer now shows the ‘MyComponent’ added as a
reference in your application. Now all of the classes, along with their
properties, methods, and events, are now available to your application.
6. Enter the following code and run
Module Module1
Sub Main()
Dim c As New MyComponent.College("SRM", "Potheri")
c.Display()
Console.ReadKey()
End Sub
End Module
Access Modifiers
Access modifiers are an integral part of object-oriented programming. They
support the concept of encapsulation, which promotes the idea of hiding
functionality. Access modifiers allow you to define who does or doesn't have
access to certain features.

In VB.NET there are 5 different types of Access Modifiers


MODIFIERS DESCRIPTION
Public There are no restrictions on accessing public members.
Private Access is limited to within the class definition. This is the
default access modifier type if none is formally specified
Protected Access is limited to within the class definition and any class
that inherits from the class
Friend Access is limited exclusively to classes defined within the
current project assembly
Protected Access is limited to the current assembly and types derived
Friend from the containing class. All members in current project and
all members in derived class
 Public
The public keyword is an access modifier for types and type members.
Public access is the most permissive access level. There are no
restrictions on accessing public members.
 Private
Private access is the least permissive access level. Private members are
accessible only within the body of the class or the struct in which they
are declared.
 Protected
A protected member is accessible from within the class in which it is
declared, and from within any class derived from the class that declared
this member. A protected member of a base class is accessible in a
derived class only if the access takes place through the derived class
type.
 Friend
The Friend keyword is an access modifier for types and type members.
We can declare a class as Friend or its member as Friend. Friend
members are accessible only within files in the same assembly (.dll). In
other words, access is limited exclusively to classes defined within the
current project assembly.
 Protected Friend
The protected friend accessibility means protected OR friend, not
protected AND friend. In other words, a protected internal member is
accessible from any class in the same assembly, including derived
classes.

You might also like