Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

NET Unit3 PDF

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

2.

4 Object and Classes


As we noted previously, one can create new reference types by defining
classes. Classes provide 'templates' from which these direct instances are
generated. Where we appeal to the relation between a class and its
corresponding reference type instances we shall say that a class specifies the
type (also that the class specifies the constitutive elements of the type).
Any type is made up of elements, which we term type members. There are
two main kinds of type members that a class can specify. Firstly, a class can
specify other types - both value and reference. This idea, that types can
contain other types, is known within the literature on object orientation as
'containment', or else 'aggregation'. Where a type contains another reference
type, we shall call it the containing type of the latter.
The second, main kind of type members that a class can specify are methods,
functions designed for reading and manipulating the value and reference types
an instance contains.
Objects

Objects in C# are created from types, just like a variable. This type of an
object is known as class. we can use class definition to instantiate objects,
which means to create a real named instance of a class.
Declaration of Classes
Class is an user-defined data type. To create a class, you start with the class
keyword followed by a name and its body delimited by curly brackets. . The
following is an example of a very simple class declaration

class classname
{
// class-body
}

The class-body contains the member data and member function of the class.
C++ programmer must note that there is no semicolon after the closing brace
of the class.

Members of Class
Class is a mechanism to implement the encapsulation, it bind the data and a
function in a single unit. Therefore data and functions are the members of
class, which is known as member data and member function.

There is an example of full class :


class Circle

{
double radius;
public void get_radius(double r)
{
radius = r;
}
public double area()
{
return ( 3.14 * r *r);
}
}

Member Access Modifiers


Access modifiers provide the accessibility control for the members of classes to
outside the class. They also provide the concept of data hiding. There are five
member access modifiers provided by the C# Language.

Modifier Accessibility
private Members only accessible with in class

public Members may accessible anywhere outside


class
protected Members only accessible with in class and
derived class
By default all member of class have private accessibility. If we want a
member to have any other accessibility, then we must specify a suitable
access modifier to it individually.
For Example:

class Demo
{
public int double d;
a;
internal
int x;
protected
float m; // private by default
}
Object Creation
In C# objects are created using the new keyword. Actually it new is an
operator, creates an object of the specified class and returns a reference to that
object. Here is an example :

public class Exercise


{
public void Welcome()
{
Console.WriteLine("This is Exercise class");
}
}
public class Class1
{
static void Main()
{
Exercise exo = new Exercise();
}
}

Constructor and Destructor


When you declare a variable of a class, a special method must be called to
initialize the members of that class. This method is automatically provided for
every class and it is called a constructor.

Default Constructor
Whenever you create a new class, a constructor is automatically provided to it.
This particular constructor is called the default constructor. You have the option
of creating it or not. Although a constructor is created for your class, you can
customize its behavior or change it tremendously.
A constructor holds the same name as its class and doesn't return any value,
not even void. Here is an example:
Like every method, a constructor can be equipped with a body. In this body,
you can access any of the member variables (or method(s)) of the same class.
When introducing classes other than the main class, we saw that, to use such a
class, you can declare its variable and allocate memory using the new operator.
You can notice that we always included the parentheses when declaring such a
variable.

Here is an example:
public class Class1
{
static void Main()
{
Exercise exo = new Exercise();
}
}
In this case, the parentheses indicate that we are calling the default constructor
to instantiate the class.
Consider the following Example:
Example
using System;
public class Exercise
{
public void Welcome()
{
Console.WriteLine("The wonderful world of C# programming");
}
public Exercise() }
{
Console.WriteLine("The Exercise class is now
available");
}
public class Class1
{
static void Main()
{
Exercise exo = new Exercise();
}
}

OUTPUT:
This shows that, when a class has been instantiated, its constructor is the first
method to be called. For this reason, you can use a constructor to initialize a
class, that is, to assign default values to its member variables. When a
constructor is used to initialize a variable declared for a class. That constructor
is referred to as an instance constructor.

Parameterized Constructor
In the previous section, we saw that there is always a default constructor for a
new class that you create; you just the option of explicitly creating one or not.
The default constructor as we saw it doesn't take arguments: this is not a rule,
it is simply assumed. Instead of a default constructor, you may want to create
a constructor that takes an argument. Here is an example:
using System;
public class Quadrilateral
{
public Quadrilateral(double side)
{…….
}
}
public class Class1
{
static void Main()
{
Quadrilateral Square = new Quadrilateral(6.55);
}
}
28
Static Constructor
Like the above described instance constructors, a static constructor is used to
initialize a class. The main difference is that a static constructor works
internally, in the class. Therefore, it is not used to initialize a variable of the
class and you can never declare a variable of a class using a static constructor.
To make a constructor static, when creating it, type the static keyword to its
left. Here is an example:
using System;
public class Quadrilateral
{
static Quadrilateral()
{
}
}
public class Class1
{
static void Main()
{
/* Use the default constructor to initialize an instance of the class */
Quadrilateral Square = new Quadrilateral();
}
}
In the above class, a static constructor is created for the class but the default
constructor is still available and it is used to instantiate the class.

Constructor Overloading
A constructor is the primary method of a class. It allows the programmer to
initialize a variable of a class when the class is instantiated. A constructor that
plays this role of initializing an instance of a class is also called an instance
constructor. Most of the time, you don't even need to create a constructor,
since one is automatically provided to any class you create. Sometimes too, as
we have seen in some classes, you need to create your own class as you judge
it necessary. And sometimes, a single constructor may not be sufficient. For
example, when creating a class, you may decide, or find out, that there must
be more than one way for a user to initialize a variable.
Like any other method, a constructor can be overloaded. In other words, you
can create a class and give it more than one constructor. The same rules used
on overloading regular methods also apply to constructors: the different
constructors must have different number of arguments or a different number of
arguments.
Example using System;
public class Applicant
{
public string FullName; public string Address; public string City; public string
State;
29
public string ZIPCode; public string Sex;
public string DateOfBirth; public int Weight; public string Height; public int
Race;
// The default constructor, used to initialize an

// Applicant instance without much information public Applicant()

{
this.FullName = "Unknown"; this.Sex = "Ungenerated";
}
// A constructor that is passed only one argument public Applicant(string n)

{
this.FullName = n;
}
// A constructor with more than one argument

// This type is suitable to completely initialize a variable public Applicant(string


n, string s, string dob)

{
this.FullName = n; this.Sex = s; this.DateOfBirth = dob;
}
}
public class Exercise
{
static Applicant RegisterPersonalInformation()
{
string name; char sex;
string gender = null; string dob;
Console.WriteLine(" ** Motor Vehicle Administration **");
Console.WriteLine("Applicant's Registration"); Console.Write("Full Name: ");
name = Console.ReadLine();
do
{
Console.Write("Sex(F=Female/M=Male): "); sex =
char.Parse(Console.ReadLine());
if( (sex != 'f') && (sex != 'F') && (sex != 'm') && (sex != 'M') )
Console.WriteLine("Please enter a valid character");
}while( (sex != 'f') && (sex != 'F') && (sex != 'm') && (sex != 'M') );
if( (sex == 'f') || sex == 'F' ) gender = "Female";
30
else if( (sex == 'm') || (sex == 'M') )
gender = "Male";
Console.Write("Date of Birth(mm/dd/yyyy): ");
dob = Console.ReadLine();
Applicant person = new Applicant(name, gender, dob);
return person;
}
static void Show(Applicant person)
{
Console.WriteLine("\n ** Motor Vehicle Administration **");
Console.WriteLine(" --- Applicant's Personal Information ---");
Console.WriteLine("Full Name: {0}", person.FullName);
Console.WriteLine("Sex: {0}", person.Sex);
Console.WriteLine("Date of Birth: {0}\n", person.DateOfBirth);
}
public static int Main()
{
Applicant App = new Applicant();
App = RegisterPersonalInformation();
Show(App);
return 0;
}
}
OUTPUT:
** Motor Vehicle Administration ** Applicant's Registration
Full Name: Dominique Monay Sex(F=Female/M=Male): d Please enter a valid
character Sex(F=Female/M=Male): M
Date of Birth(mm/dd/yyyy): 06/10/1972
** Motor Vehicle Administration **
--- Applicant's Personal Information ---
Full Name: Dominique Monay Sex: Male
Date of Birth: 06/10/1972

Destructor
While a constructor is a method used to initialize an instance of a class, a
destructor is used to destruct an instance of class when that variable is not
used anymore. Like the constructor, the destructor has the same name as the
class. To indicate that the method is a destructor, its name is preceded with a
tilde.
Example using System;
class SampleClass
31
{ constructor
public SampleClass()
/ {
/ Console.WriteLine("SampleClass -
Constructor");
C }
~SampleClass()
{
Console.WriteLine("Destructor of
SampleClass");
}
}
public class NewProject
{
static void Main()
{
SampleClass Sample = new SampleClass();
Console.WriteLine(―Welcome‖);
}
}

OUTPUT:
SampleClass - Constructor Welcome
Destructor of SampleClass
Like a (default) constructor, a destructor is automatically created for your class
but you can also create it if you want. A class can have only one constructor. If
you don't create it, the compiler would create it for your class. If you create it,
the compiler would not create another. A destructor cannot have an access
level. A destructor is called when the memory that a class was used is no longer
needed. This is done automatically by the compiler. For this reason, you will
hardly need to create a constructor, since its job is automatically taken care of
behind the scenes by the compiler.

2.5 Inheritance and Polymorphism


Inheritance means taking an existing class and adding functionality by deriving
a new class from it.
The class you start with is called the base class, and the new class you create is
called the derived class.
When you derive a class from another class, the new class gets all the
functionality of the base class plus whatever new features you add. You can add
data members and functions to the new class, but you cannot remove anything
from what the base class offers.
In C# inheritance may be implemented in different combinations as illustrated
in figure 6.1and they include :
1) Single Inheritance
2) Multilevel Inheritance
3) Multiple Inheritance
4) Hierarchical Inheritance

Abstract Classes
In C#, you can create a class whose role is only meant to provide fundamental
characteristics for other classes. This type of class cannot be used to declare a
variable of the object. Such a class is referred to as abstract. Therefore, an
abstract class can be created only to serve as a parent class for others. To
create an abstract class, type the abstract keyword to the left of its name.
Here is an example:
abstract class Ball
{
protected int TypeOfSport;
protected string Dimensions;
}

The important features of abstract class are:


The abstract class may contain the one or more abstract methods
The abstract class cannot be instantiate in the other classes
If your are inheriting the abstract class in other class, you should implement
all the abstract methods in the derived class.

Example
using System;
abstract class First
{
protected string s = ― ‖;
public abstract void SayHello();
}
class Second : First
{
public override void SayHello()
{
s = ―Hello World‖; Console.WriteLine(―{0}‖,s);
}
}
class mainclass
{
public static void Main()
{
Second S = new Second();
S.SayHello();
}
}
OUTPUT:
Hello World

In class First we define abstract method called SayHello(). But there is no


implementation. The class Second derived from the class First and inherits
the abstract class, where we overriding the SayHello() method.

Polymorphism
Polymorphism is a feature to use one name in many forms. There
Polymorphism can be achieved in following ways in c#:
Method Overloading

Method overloading ,discussed in chapter 5, means one method name with


different arguments. Method overriding and hiding makes use of the
following three method-head keywords

The main difference between hiding and overriding relates to the choice of
which method to call where the declared class of a variable is different to the
run-time class of the object it references. This point is explained further
below.
Method Overriding
Suppose that we define a Square class which inherits from a Rectangle class
(a square being a special case of a rectangle). Each of these classes also
specifies a 'getArea' instance method, returning the area of the given
instance.
For the Square class to 'override' the Rectangle class' getArea method, the
Rectangle class' method must have first declared that it is happy to be
overridden. One way in which it can do this is with the 'virtual' keyword.
So, for instance, the Rectangle class' getArea method might be specified like
this:
public virtual double getArea() return length * width;
}
To override this method the Square class would then specify the overriding
method with the 'override' keyword. For example:
public override double getArea()
{
return length * length;
}
Note that for one method to override another, the overridden method must
not be static, and it must be declared as either 'virtual', 'abstract' or
'override'. Furthermore, the access modifiers for each method must be the
same.
The major implication of the specifications above is that if we construct a
new Square instance and then call its 'getArea' method, the method actually
called will be the Square instance's getArea method. So, for instance, if we
run the following code:
Square sq = new Square(5); double area = sq.getArea();
then the getArea method called on the second line will be the method
defined in the Square class. There is, however, a more subtle point. To show
this, suppose that we declare two variables in the following way:
Square sq = new Square(4); Rectangle r = sq;
Here variable r refers to sq as a Rectangle instance (possible because the
Square class derives from the Rectangle class). We can now raise the
question: if we run the following code
double area = r.getArea();
then which getArea method is actually called - the Square class method or
the Rectangle class method?
The answer in this case is that the Square class method would still be called.
Because the Square class' getArea method 'overrides' the corresponding
method in the Rectangle class, calls to this method on a Square instance
always 'slide through' to the overriding method.
Method Hiding
Where one method 'hides' another, the hidden method does not need to be
declared with any special keyword. Instead, the hiding method just declares
itself as 'new'. So, where the Square class hides the Rectangle class'
getArea method, the two methods might just be written thus:
public double getArea() // in Rectangle
{
return length * width;
}
public new double getArea() // in Square
{
return length * length;
}
Note that a method can 'hide' another one without the access modifiers of
these methods being the same. So, for instance, the Square's getArea
method could be declared as private, viz:
private new double getArea()
{
return length * length;
}
This leads us to an important point. A 'new' method only hides a super-class
method with a scope defined by its access modifier. Specifically, where the
access level of the hiding method is 'private', as in the method just
described, this method only hides the super-class method for the particular
class in which it is defined.
To make this point more concrete, suppose that we introduced a further
class, SpecialSquare, which inherits from Square. Suppose further that
SpecialSquare does not overwrite the getArea method. In this case, because
Square's getArea method is defined as private, SpecialSquare inherits its
getArea method directly from the Rectangle class (where the getArea
method is public).
The final point to note about method hiding is that method calls do not
always 'slide through' in the way that they do with virtual methods. So, if we
declare two variables thus:
Square sq = new Square(4);
Rectangle r = sq;
then run the code
double area = r.getArea();
the getArea method run will be that defined in the Rectangle class, not the
Square class.

You might also like