VB.NET Quick Tips and Tricks

OOPs Concepts

Note: For all my examples (Most) I use free C# online compiler. You can test these examples using this free editor. If you have any problem, please feel free to email me if you run across any problems. 

Keep in mind if you understand the concept, that will make it lot easier to explain the answer. 

All the questions are recorded in audio format. Please send me a query for your free copy.  

C# Online Compiler | .NET Fiddle (dotnetfiddle.net)


1. What is OOPs?

Object-Oriented Programming (OOP) is a software development model that organizes software design around data, or objects, rather than functions and logic. An object can be defined as a data field that has unique attributes and behavior. OOP focuses on the objects that developers want to manipulate rather than the logic required to manipulate them.  It is built on the concept of "Classes" and "Objects”.
The structure, or building blocks, of object-oriented programming include the following: (Here is general idea on these building blocks, we will go in more details on each one of them in coming questions. For answering first questions, only replying to the initial part of the answer will suffice.)

·      Classes are user-defined data types that act as the blueprint for individual objects, attributes, and methods.

·      Objects are instances of a class created with specifically defined data. Objects can correspond to real-world objects or an abstract entity. When class is defined initially, the description is the only object that is defined.

·      Methods are functions that are defined inside a class that describe the behaviors of an object. Each method contained in class definitions starts with a reference to an instance object. Additionally, the subroutines contained in an object are called instance methods. Programmers use methods for reusability or keeping functionality encapsulated inside one object at a time.

·      Attributes are defined in the class template and represent the state of an object. Objects will have data stored in the attributes field. Class attributes belong to the class itself. 

Excellent resource to understand OOPs in detail with real world example: 

What is Object Oriented Programming

C# Class & Object Tutorial with Examples (guru99.com)

What is Object-Oriented Programming (OOP)? (techtarget.com)

2. What is a class?
Class is a template for an object. Suppose that someone builds a paper pattern for a shirt. All the shirts done with the same paper pattern will be identical (same design, size, etc.). In this sample, the paper pattern is the class and the shirt is the object. To build the same exact shirt over and over, you need the paper pattern as a template. Another great example are house plans and blueprints. The plans and blueprints define the number of rooms, the size of the kitchen, the number of floors, and more. In this real world sample, the house plans and blueprints are the class and the house is the object. In OOP you program a class as a template for a specific object or groups ob objects that will always have the same features.

Excellent explanation: 

Class and Objects in C# with Examples - Dot Net Tutorials

   Using System;

Namespace ClassObjectsDemo

{

    Class Program

    {

        Static void Main(String[] args)

        {

            //Creating object

            Calculator calObject = New Calculator();


            //Accessing Calculator class member using Calculator class object

            int result = calObject.CalculateSum(10, 20);


            Console.WriteLine(result);

            Console.ReadKey();

        }

    }


    //Defining class Or blueprint Or template

    Public Class Calculator

    {

        Public int CalculateSum(int no1, int no2)

        {

            Return no1 + no2;

        }

    }

}


3. What are the different members of the class?

"Namespace: The namespace is a keyword that defines a distinctive name or last name for the class. A namespace categorizes and organizes the library (assembly) where the class belongs and avoids collisions with classes that share the same name.

Class declaration: Line of code where the class name and type are defined.

Fields: Set of variables declared in a class block.

Constants: Set of constants declared in a class block.

Constructors: A method or group of methods that contains code to initialize the class.

Properties: The set of descriptive data of an object.

Events: Program responses that get fired after a user or application action.

Methods: Set of functions of the class.

Destructor: A method that is called when the class is destroyed. In managed code, the Garbage Collector is in charge of destroying objects; however, in some cases developers need to take extra actions when objects are being released, such as freeing handles or deallocating unmanaged objects. In .NET, there is no concept of deterministic destructors. The Garbage Collector will call the Finalize() method at a non-deterministic time while reclaiming memory for the application"

4. List all class access modifiers?

• Private

• Protected

• Friend (internal in C#)

• Protected friend (protected internal in C#)

• Public


20. Polymorphism?

Best explanation: C# Polymorphism with Examples - Tutlane

·       Poly means "Many" and Morph means "change as per situation". It is an ability of an object to behave differently in different conditions.  Inheritance lets us inherit fields and methods from another class. Polymorphism uses those methods to perform different tasks. In c#, polymorphism provides an ability for the classes to implement different methods called through the same name. It also provides an ability to invoke a derived class's methods through base class reference during runtime based on our requirements.

·       C# provides an option to override the base class method, by adding the virtual keyword to the method inside the base class, and by using the override keyword for each derived class methods. In short:

·       At run time, objects of a derived class may be treated as objects of a base class in places such as method parameters and collections or arrays. When this polymorphism occurs, the object's declared type is no longer identical to its run-time type.

·       Base classes may define and implement virtual methods, and derived classes can override them, which means they provide their own definition and implementation. At run-time, when client code calls the method, the CLR looks up the run-time type of the object and invokes that override of the virtual method. In your source code you can call a method on a base class and cause a derived class's version of the method to be executed.

Source: Polymorphism | Microsoft Docs

For example, think of a base class called Teacher that has a method called subject(). Derived classes of Teachers could be Math Teacher, English Teacher, Science Teacher etc. and they also have their own implementation of an method subject()

using System;

public class Program

{

public static void Main()

{

  Teacher myTeacher = new Teacher();  // Create a Animal object

      English myEnglishTeacher = new English();  // Create a Pig object

      Math myMathTeacher = new Math();  // Create a Dog object

      myTeacher.teachSubject();

      myEnglishTeacher.teachSubject();

      myMathTeacher.teachSubject();

}

}

class Teacher  // Base class (parent) 

  {

    public virtual void teachSubject()

    {

      Console.WriteLine("What subject do you teach");

    }

  }

  class English : Teacher  // Derived class (child) 

  {

    public override void teachSubject()

    {

      Console.WriteLine("I teach English");

    }

  }

  class Math : Teacher  // Derived class (child) 

  {

    public override void teachSubject()

    {

      Console.WriteLine("I teach Math");

    }

  }


 Ques: What is the difference between compile time and runtime? 


Source: Compile time vs Runtime | Top 6 Comparisons of Compile time vs Runtime (educba.com)

GenreCompile-time

Runtime

When does the time start?This is when the code is translated from a programming language to a language that a machine understands.This is when a code is run in the runtime environment and starts from the time code execution starts till the point the user or OS stops the code.
Where does it come in the hierarchy?This occurs well in advance in software development.After the software development is complete, it comes into play when the code is executed in a runtime environment.
PolymorphismThe code understands and checks for the object, which invokes a method.The code cannot understand which object is invoking the method, and code is compiled without knowing that information.
Compile-time error – ReferenceThese errors are referenced to an error in syntax or semantics.These errors are a reference to the execution of the code in a runtime environment.
Compile-time error – DetectThis error can be detected during software development.This error might come up even when the code is run in a runtime environment, even if it has passed in the local.
Compile-time error – FixThese errors can be fixed during the code development itself.These errors are rather difficult to interpret during development and can be fixed only when it starts showing up in the runtime environment.



5. Explain various access modifiers?

Public: Classes and class members marked with Public access modifier are available in the same class, all the classes from the same project and to all other projects as well. You can use Public only at module, interface, or namespace level. This means you can declare a public element at the level of a source file or namespace, or inside an interface, module, class, or structure, but not in a procedure. Private keyword in the declaration statement specifies that the elements can be accessed only from within the same module, class, or structure. The following code shows a sample Private declaration. You can use Private only at module level. This means you can declare a private element inside a module, class, or structure, but not at the level of a source file or namespace, inside an interface, or in a procedure. Private numberForMeOnly As Integer

The Protected keyword in the declaration statement specifies that the elements can be accessed only from within the same class, or from a class derived from this class. The following code shows a sample Protected declaration.

Eg: Protected Class classForMyHeirs

You can use Protected only at class level, and only when you declare a member of a class. This means you can declare a protected element in a class, but not at the level of a source file or namespace, or inside an interface, module, structure, or procedure. The Friend keyword in the declaration statement specifies that the elements can be accessed from within the same assembly, but not from outside the assembly.

Friend stringForThisProject As String

You can use Friend only at module, interface, or namespace level. This means you can declare a friend element at the level of a source file or namespace, or inside an interface, module, class, or structure, but not in a procedure.

Protected Friend:The Protected and Friend keywords together in the declaration statement specify that the elements can be accessed either from derived classes or from within the same assembly, or both.

Protected Friend stringForProjectAndHeirs As String

You can use Protected Friend only at class level, and only when you declare a member of a class. This means you can declare a protected friend element in a class, but not at the level of a source file or namespace, or inside an interface, module, structure, or procedure.

6. What is Dim statement used for?

Declares and allocates storage space for one or more variables.

7. What is object?

Object is instance of a class. An instance is created using a Dim statement and the New keyword.

8. Difference between Association, Aggregation and Composition?

Association is a relationship where all object have their own lifecycle and there is no owner. Let’s take an example of Teacher and Student. Multiple students can associate with single teacher and single student can associate with multiple teachers but there is no ownership between the objects and both have their own lifecycle. Both can create and delete independently.

Points:

• Is a Relationship between objects.

• Objects have independent lifecycles.

• There is no owner.

• Objects can create and delete independently.

Aggregation

Aggregation is a specialize form of Association where all object have their own lifecycle but there is ownership and child object cannot belongs to another parent object. Let’s take an example of Department and teacher. A single teacher cannot belongs to multiple departments, but if we delete the department teacher object will not destroy. We can think about “has-a” relationship.

Points:

• Specialize form of Association.

• has-a relationship between objects

• Object has independent life-cycles

• Parent-Child relationship

Composition

Composition is again specialize form of Aggregation. It is a strong type of Aggregation. Child object dose not have their lifecycle and if parent object deletes all child object will also be deleted. Let’s take again an example of relationship between House and rooms. House can contain multiple rooms there is no independent life of room and any room cannot belongs to two different house if we delete the house room will automatically delete. Let’s take another example relationship between Questions and options. Single questions can have multiple options and option cannot belong to multiple questions. If we delete questions options will automatically delete.

Points:

• Specialize form of Aggregation

• Strong Type of Aggregation.

• Parent-Child relationship

• Only parent object has independent life-cycle. "

So in summary, we can say that aggregation is a special kind of an association and composition is a special kind of an aggregation. (Association->Aggregation->Composition)

9. Difference between overloading and overriding?

"1. Overloading deals with multiple methods in the same class with the same name but different signatures

Overriding deals with two methods, one in a parent class and one in a child class, that have the same signature

2. Overloading lets you define a similar operation in different ways for different data

Overriding lets you define a similar operation in different ways for different object types."

10. What are basic concepts of Oops?

Abstraction, Encapsulation, Inheritance and Polymorphism are the core OOP’s concepts.

11. Difference between classes and Structs

•A struct is a value type, while a class is a reference type.

•When we instantiate a class, memory will be allocated on the heap. When struct gets initiated, it gets memory on the stack.

•Classes can have explicit parameter less constructors. But structs cannot have this.

•Classes support inheritance. But there is no inheritance for structs. A struct cannot inherit from another struct or class, and it cannot be the base of a class. Like classes, structures can implement interfaces.

•We can assign null variable to class. But we cannot assign null to a struct variable, since structs are value type.

•We can declare a destructor in class but cannot in struct."



12. What is a structure?

"Structures are complex data types that encapsulate small pieces of tightly related data items. As with Classes, Structures can contain data members as well as member methods to work with data inside a structure. Since the in-memory representation of Structure is 'value type', memory management is handled efficiently. The following example shows how to encapsulate product info into a structure called Product.

Private Structure Product

'Declare data members

Public ProductID as Integer

Public ProductName as String

Private UnitPrice as Single

'Declare code members

Public Function GetPrice() as Single

GetPrice = UnitPrice

End Function

End Structure"

13. Concept of Generalization and specialization in OOPs?

The concept of generalization in OOP means that an object encapsulates common state an behavior for a category of objects. The general object in this sample is the geometric shape. Most geometric shapes have area, perimeter, and color. The concept of specialization in OOP means that an object can inherit the common state and behavior of a generic object; however, each object needs to define its own special and particular state an behavior. In Figure 1, each shape has its own color. Each shape has also particular formulas to calculate its area and perimeter.

14. What is meant by Inheritance?

"Inheritance is a relationship among classes, wherein one class shares the structure or behaviour defined in another class.The most common real world sample to explain inheritance is the geometric shapes object model. Squares, circles, triangles, rectangles, pentagons, hexagons, and octagons are geometric shapes. The following figure shows a sample set of geometric figures:

Inheritance makes code elegant and less repetitive. If we know that all shapes have color, should we program a color attribute for each shape? The answer is no! Would it be a better idea to create a shape class that has a color attribute and to make all the specialized shapes to inherit the color attribute? The answer is yes! An object model for this sample could have a shape parent class and a derived class for each specific shape. The following UML class diagram shows the set of classes needed to model the geometric shapes sample. Observe the field, properties, and methods for each class:”

15. What is a Sealed Class?

A sealed class is a class that does not allow inheritance. Some object model designs need to allow the creation of new instances but not inheritance, if this is the case, the class should be declared as sealed. The main purpose of a sealed class to take away the inheritance feature from the user so they cannot derive a class from a sealed class. One of the best usage of sealed classes is when you have a class with static members. For example, the Pens and Brushes classes of the System.Drawing namespace. The Pens class represent the pens for standard colors. This class has only static members. For example, Pens.Blue represents a pen with blue color. Similarly, the Brushes class represents standard brushes. The Brushes.Blue represents a brush with blue color. So when you're designing your application, you may keep in mind that you have sealed classes to seal user's boundaries. In the next article of this series, I will discuss some usage of abstract classes.

16. Abstraction?

Abstraction defines the essential characteristics of an object that distinguish it from all other kinds of objects. Abstraction provides crisply-defined conceptual boundaries relative to the perspective of the viewer. It’s the process of focusing on the essential characteristics of an object. Abstraction is one of the fundamental elements of the object model.

17. What is an Abstract Class?

An abstract class is a parent class that allows inheritance but can never be instantiated. Abstract classes contain one or more abstract methods that do not have implementation. Abstract classes allow specialization of inherited classes.

"Figure above shows a Shape class, which is an abstract class. In the real world, you never calculate the area or perimeter of a generic shape, you must know what kind of geometric shape you have because each shape (eg. square, circle, rectangle, etc.) has its own area and perimeter formulas. The parent class shape forces all derived classes to define the behavior for CalculateArea() and CalculatePerimeter(). Another great example is a bank account. People own savings accounts, checking accounts, credit accounts, investment accounts, but not generic bank accounts. In this case, a bank account can be an abstract class and all the other specialized bank accounts inherit from bank account. To create an abstract class in VB.NET, the class declaration should be done as:

MustInherit Class Shape

To following code shows a sample implementation of an abstract class:"

"Namespace DotNetTreats.OOSE.OOPSamples

Public MustInherit Class Shape

Private _area As Single

Private _color As System.Drawing.Color

Private _perimeter As Single

Public Property Area() As Single

Get

Return _area

End Get

Set "

" _area = value

End Set

End Property

Public Property Color() As System.Drawing.Color

Get

Return _color

End Get

Set

_color = value

End Set

End Property

Public Property Perimeter() As Single

Get

Return _perimeter

End Get

Set

_perimeter = value

End Set

End Property

Public MustOverride Sub CalculateArea()

Public MustOverride Sub CalculatePerimeter()

End Class

End Namespace"


18. Encapsulation?

"Encapsulation is the ability of the object to hide its data and the methods from rest of the world. It means that in Object-Oriented approach, an object is encapsulated from any other object there is. Everything inside an object, cannot be ""touched"" (accessed) by any other object within the program, unless it is permitted to be.

So whenever we want any property of an object (constants, variables, functions, or procedures) to be revealed to others, we just have to set it as a ""Public"" property (usually done by typing the word ""Public"" in the beginning of its declaration). And when we don't want it to be, we set it as ""Private"".

And encapsulation is an advantage because as the programming goes on, we don't have to worry about the same constant, variable, function, or procedure's name within the whole program. Every object has its own properties, and can only be accessed if it was allowed. "

19. Difference between Encapsulation and Abstraction?

"Actually encapsulation compliments abstraction and both are features of Object Oriented Programming .

Encapsulation means the ability to encapsulate or keep data members (class level variable) and Member function (sub/functions ) together under one entity that is class.

Abstraction is the ability to present only necessary information to the user of the class and hence hiding or abstracting the detail. So abstraction is achieved using encapsulation.

For example You create a class and its data members and member function which uses these data members. TO use this class u create object so the user of the object doesn’t have to know the inner details of the class all he sees is the public member function (sub/function of class)."



21. Interface?

"Interfaces allow us to create definitions for component interaction. They also provide another way of implementing polymorphism. Through interfaces, we specify methods that a component must implement without actually specifying how the method is implemented. We just specify the methods in an interface and leave it to the class to implement those methods. Visual Basic .NET does not support multiple inheritance directly but using interfaces we can achieve multiple inheritance. We use the Interface keyword to create an interface and implements keyword to implement the interface. Once you create an interface you need to implement all the methods specified in that interface. The following code demonstrates the use of interface.

Imports System.Console

Module Module1

Sub Main()

Dim OneObj As New One()

Dim TwoObj As New Two()

'creating objects of class One and Two"



"OneObj.disp()

OneObj.multiply()

TwoObj.disp()

TwoObj.multiply()

'accessing the methods from classes as specified in the interface

End Sub

End Module

Public Interface Test

'creating an Interface named Test

Sub disp()

Function Multiply() As Double

'specifying two methods in an interface

End Interface

Public Class One

Implements Test

'implementing interface in class One

Public i As Double = 12

Public j As Double = 12.17

Sub disp() Implements Test.disp

'implementing the method specified in interface

WriteLine(""sum of i+j is"" & i + j)

Read()

End Sub"

"Public Function multiply() As Double Implements Test.Multiply

'implementing the method specified in interface

WriteLine(i * j)

Read()

End Function

End Class

Public Class Two

Implements Test

'implementing the interface in class Two"



"Public a As Double = 20

Public b As Double = 32.17

Sub disp() Implements Test.disp

WriteLine(""Welcome to Interfaces"")

Read()

End Sub

Public Function multiply() As Double Implements Test.Multiply

WriteLine(a * b)

Read()

End Function

End Class "



22. What is the base class?

Most generalized class in Oops is the base class. Eg: System.Object is base class of vb.net framework.

23. What is a constructor?

Constructor is an operation that creates an object and/or initialises its state. In vb.net "New" keyword is used to create an object.

24. What is a Destructor?

"Destructor is an operation that frees the state of an object and/or destroys the object itself. The destructor is the last method run by a class. This is called Finalize in VB.NET and it’s called whenever the .NET runtime is told directly or otherwise determines that an object is no longer required. Common uses for the Finalize method is to decrement or increment counters or release resources.

The VB.NET compiler creates a default Finalize method that, behind the scenes, will release variables. However, there may be cases where it’s preferable to have your own code in this routine.

When you do this, you have to use the Overrides keyword in your declaration, like so: Protected Overrides Sub Finalize ()

No comments:

Post a Comment