Showing posts with label Oops Basics. Show all posts
Showing posts with label Oops Basics. Show all posts

Oops Basics part 3

21) why have interfaces?

There are often situations in which we need to know that the class implements certain features in order to be able to use a class in a certain way. An example is provided by the foreach loop in C#. In principle, it is possible to use foreach to iterate through a class instance, provided that that class is able to act as if it is a collection. How can the .NET runtime tell whether a class instance represents a collection? It queries the instance to find out whether it implements the System.Collections.IEnumerable interface.
If it does, then the runtime uses the methods on this interface to iterate through the members of the collection. If it doesn’t, then foreach will raise an exception.


A second reason for using interfaces is for interoperability with COM. Before the advent of .NET, COM, and its later versions DCOM and COM+, provided the main way that applications could communicate with each other on the Windows platform, and the particular object model that COM used was heavily dependent on interfaces. Indeed, it was through COM that the concept of an interface first became commonly known.

However, that C# interfaces are not the same as COM interfaces. COM interfaces have very strict requirements, such as that they must use GUIDs as identifiers, which are not necessarily present in C# interfaces. However, using attributes, it is possible to dress up a C# interface so it acts like a COM interface, and hence provide compatibility with COM.



22) Construction and Disposal

Most modern OOP languages support the ability to construction and destruction of objects.

This support happens through something called a constructor. A constructor
is a special method called automatically whenever an object of a given class is created. You don’t
have to write a constructor for a class, but if you want some custom initialization to take place automatically, you should place the relevant code in the constructor.

Similarly, A destructor is a method called automatically whenever an object is destroyed (the variable goes out of scope). Reclaiming memory aside, destructors are particularly useful for classes that represent a connection to a database, or an open file, or those that have methods to read from and write to the database/file. In that case, the destructor can be used to make sure that you don’t leave any database connections or file handle hanging open when the object goes out of scope.

23 ) It’s not necessary to provide a constructor for your class, far. In general, if you don’t explicitly supply any constructor, the compiler will just make up a default one for you behind the scenes. It’ll be a very basic constructor that just initializes all the member fields to their normal default values (empty string for strings, zero for numeric data types, and false for bools).

Oops basics part 2

we aim to write easily maintainable and reusable pieces of code that can perform collectively very complex tasks.

11) Properties :

Properties are in extremely common use, and can significantly simplify the external user interface exposed by classes. Properties exist for the situation in which you want to make a method call look like a field. A property is a method or pair of methods that are exposed to the outside world as if they are fields.

Example :


12) Data encapsulation :
In OOP, we aim to make it so that users of objects only need to know what an object does, not how it does it. So making fields directly accessible to users defeats the ideology behind OOP.

If we make fields directly visible to external users, we lose control over what they do to the fields. They might modify the fields in such a way as to break the intended functionality of the object (give the fields in appropriate values, let’s say).

However, if we use properties to control access to a field, this is not a problem because we can add functionality to the property that checks for inappropriate values. Related to this, we can also provide read-only properties by omitting the set accessor completely. The principle of hiding fields from client code in this way is known as data encapsulation.


13) Inheritance

C# is it supports both types of inheritance. implementation inheritance & interface inheritence

Example

public class Nevermore60Customer : Customer
{
}
This tells the compiler that Nevermore60Customer is derived from Customer or we can say that each member of Customer is inherited in Nevermore60Customer. Also, Nevermore60Customer is said to be a derived class, while Customer is said to be the base class

The base class itself is never implicitly modified in any way by the existence of the derived class. This must always be the case, because when you code the base class, you don’t necessarily know what other derived classes might be added in the future—and you wouldn’t want your code to be broken when someone adds a derived class!

Override keyword :

access modifier protected :

It indicates that any class that is derived
from Customer, as well as Customer itself, should be allowed access to this member. The member is still invisible, however, to code in any other class that is not derived from Customer. Essentially, we’re assuming that, because of the close relationship between a class and its derived class, it’s fine for the derived class to know a bit about the internal workings of the base class, at least as far as protected members are concerned.


virtual keyword:

C# will not allow derived classes to override a method unless that method has been declared as virtual in the base class.



Note : As a rule that is enforced by .NET and C#: All .NET classes must ultimately derive from a base class called Object. In C# code, if you write a class and do not specify a base class, the compiler will supply System.Object as the base class by default.

This means that all objects in the .NET Framework have certain methods inherited from the Object class, including the ToString() and GetType() methods



14 ) Single and multiple inheritance :

In C#, each derived class can only inherit from one base class (although we can create as many different classes that are derived from the same base class as we want). The terminology to describe this is single inheritance. Some other languages, including C++, allow you to write classes that have more than one base class, which is known as multiple inheritance.

15) Method Hiding

Even if a method has not been declared as virtual in a base class, it is still possible to provide another method with the same signature in a derived class. The signature of a method is the set of all information needed to describe how to call that method: its name, number of parameters, and parameter types. However, the new method will not override the method in the base class. Rather, it is said to hide the base class method.

If a method hides a method in a base class, then you should normally add the keyword new to its definition. Not doing so does not constitute an error, but it will cause the compiler to give you a warning.

16) Abstract class

Every time you defined a class you will actually create instances of that class, but that’s not always the case. In many situations, you’ll define a very generic class from which you intend to derive other, more specialized classes but don’t ever intend to actually use. C# provides the keyword abstract for this purpose. If a class is declared as abstract it is not possible to instantiate it.

Example :

abstract class MyBaseClass

In this case the following statement will not compile:

MyBaseClass MyBaseRef = new MyBaseClass();

However, it’s perfectly legitimate to have MyBaseClass references, so long as they only point to derived classes. For example, you can derive a new class from MyBaseClass:

class MyDerivedClass : MyBaseClass
{
...
In this case, the following is perfectly valid code:

MyBaseClass myBaseRef;
myBaseRef = new MyDerivedClass();

17) Abstract methods

It’s also possible to define a method as abstract. This means that the method is treated as a virtual method, and that you are not actually implementing the method in that class, on the assumption that it will be overridden in all derived classes. If you declare a method as abstract you do not need to supply a method body:

Note : If any method in a class is abstract, then that implies the class itself should be abstract, and the compiler will raise an error if the class is not so declared. Also, any non-abstract class that is derived from this class must override the abstract method. These rules prevent you from ever actually instantiating a class that doesn’t have implementations of all its methods.


18) What is the use of abstract methods and classes?

They are extremely useful for two reasons. One is that they often allow a better design of class hierarchy, in which the hierarchy more closely reflects the situation you are trying to model. The other is that the use of abstract classes can shift certain potential bugs from hard-to-locate runtime errors into easy-to-locate compile-time errors.


19) Sealed Classes and Methods

Methods and classes that cannot be overridden or inherited from.C# also supports declaring an individual override method as sealed, preventing any further overrides
of it.

The most likely situation when you’ll mark a class or method as sealed will be if it is very much internal to the operation of the library, class, or other classes that you are writing, so you are fairly sure that any attempt to override some of its functionality causes problems. You might also mark a class or method as sealed for commercial reasons, in order to prevent a third party from extending your classes in a manner that is contrary to the licensing agreements.


20) Interfaces

In general, an interface is a contract that says that a class must implement certain features (usually methods and properties), but which doesn’t specify any implementations of those methods and properties. Therefore you don’t instantiate an interface; instead a class can declare that it implements one or more interfaces. In C#, as in most languages that support interfaces, this essentially means that the class inherits from the interface.

Example :

interface IEnumerator
{
// Properties
object Current {get; }

// Methods
bool MoveNext();
void Reset();
}

Oops basics part 1

we aim to write easily maintainable and reusable pieces of code that can perform collectively very complex tasks.

1) An object is anything that is identifiably a single material item. An object can be a car, a
house, a book, a document or a car radio. Most people don’t know exactly how a car radio works; however, they do know what it does and how to operate it.

2) In programming we break each program into lots of units and design each unit to perform a clearly specified role within the program. That’s basically what an object is.

3) If oops principals are used properly while programming then it becomes easier for multiple developers to work together, since they can work on different objects in the code; all they need to know is what an object can do and how to interface with it. They don’t have to worry about the details of how the underlying code works.

4) Difference between a class and object

In programming, we need to distinguish between a class and an object. A class is the generic definition of what an object is—a template. For example, a class could be “car radio”—the abstract idea of a car radio. The class specifies what properties an object must have to qualify as a car radio.


5) Class members

In general, a class is defined by its fields and methods. there are two sides to an object: what it does, which is usually publicly known, and how it works, which is usually hidden.
In programming, the “what it does” is normally represented in the first instance by methods, which are blocks of functionality that you can use. A method is just C# parlance for a function. The “how it works” is represented both by methods and by any data (variables) that the object stores. In C# the terminology is fields

6) Access Modifiers

Marking a field or method as private effectively ensures that that field or method will be part of the internal working of the class, as opposed to the external interface. The advantage of this is that if you d ecide to change the internal working (perhaps you later decide not to store password as a string but to use some other more specialized data type), you can just make the change without breaking the code out side the Authenticator class definition—nothing from outside of this class can access this field.



7) Creating a class instance

Authenticator myAccess = new Authenticator();

[ = new Authenticator() ] is a part of C# syntax, and is there because in C#, classes are always
accessed by reference.

We could actually use the following line if we just wanted to declare a new Authenticator object called myAccess:

Authenticator myAccess;

This declaration can hold a reference to an Authenticator object, without actually creating any object (in much the same way that the line Dim obj As Object in Visual Basic doesn’t actually create any object).

The new operator in C# is what actually instantiates an Authenticator object.




8) Why do we decalre some fields as static?

To indicate that a field should only be stored once, no matter how many instances of the class we create, we place the keyword static in front of the field declaration in our code:

private static uint minPasswordLength = 6;

By declaring the field as static, we ensure that it is only stored once, and this field is shared among all instances of the class. Fields declared with the static keyword are referred to as
static fields or static data, while fields that are not declared as static are referred to as instance fields or instance data

Important : If a field has been declared as static, then it exists when your program is running from the moment that the particular module or assembly containing the definition of the class is loaded—that is as soon as your code tries to use something from that assembly, so you can always guarantee a static variable is there when you want to refer to it. This is independent of whether you actually create any instances of that class. By contrast, instance fields only exist when there are variables of that class currently in scope—one set of instance fields for each variable.


Also : static keyword is independent of the accessibility of the member to which it
applies. A class member can be public static or private static.

Also : However, just as with fields, it is possible to declare methods as static, provided that they do not attempt to access any instance data or other instance methods.



9) Ovwerloading a method :

To overload a method is to create several methods each with the same name, but each with a different signature. The reason why you might want to use overloading is best explained with an example. Consider how in C# we write data to the command line, using the Console.WriteLine() method.

Console.WriteLine() can display int, strings and lot of other datatypes since there are many Console.WriteLine() overloads

When to use overloading : Generally, you should consider overloading a method when you need a number of methods that take different parameters, but conceptually do the same thing, as with Console.WriteLine() above.


10) Different output types : Out parameter

occasionally you might have a method that calculates or obtains some quantity, and depending on the circumstances, you might want this to be returned in more than one way. You cannot distinguish overloads using the return type of a method. However, you can do so using out parameters.

void GetAircraftLocation(DateTime Time, out string Location)
{
...
}
void GetAircraftLocation(DateTime Time, out float Latitude, out float Longitude)
{
...
}

Note: however, that in most cases using overloads to obtain different out parameters does not lead to an architecturally neat design. In the above example, a better design would perhaps involve defining a Location struct that contains the location string as well as the latitude and longitude and returning this from the method call, hence avoiding the need for overloads.