Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
Лаба №1 / books / csharp_ebook.pdf
Скачиваний:
77
Добавлен:
03.03.2016
Размер:
3.69 Mб
Скачать

Programmers Heaven: C# School

Protected Access Modifier

In our Student class, registrationNumber is made private and has only the get {} property so that no user of the Student class can modify the registrationNumber outside the class. It might be possible that we need to modify this field (registrationNumber) in our SchoolStudent class, but we can not do this. C# provides the protected access modifier just for this. protected members of the class can be accessed either inside the containing class or inside its sub-class. Users still won't be able to call the protected members through object references and if one tries to do so, the compiler would complain and generate an error.

Suppose we have a class A with a protected method DoWork()

class A

{

protected void DoWork()

{

Console.WriteLine("DoWork called...");

}

}

If we try to call DoWork in the Main() method of the Test class, the compiler will generate an error.

class Test

{

static void Main(string [] args)

{

A a = new A(); a.DoWork();

}

}

When we try to compile it, the compiler says:

'CSharpSchool.A.DoWork()' is inaccessible due to its protection level

But, if we declare another class, B which inherits A then this class can call the DoWork() method inside its body.

class B : A

{

public B()

{

DoWork();

}

}

87

Programmers Heaven: C# School

Here we inherited the class B from the class A and called the DoWork() from its base-class (A) in its constructor. Now, when we write

static void Main(string [] args)

{

B b = new B();

}

The result will be:

DoWork called...

Press any key to continue

It shows that we can access protected members of a class inside its sub-classes. Note that it is still wrong to write

static void Main(string [] args)

{

B b = new B();

 

b.DoWork();

// error

}

We can not access protected members even with the reference of the sub-class.

The Protected internal Access Modifier

In a similar way, the protected internal access modifier allows a member (field, property and method) to be accessed:

Inside the containing class, or

Inside the same project, or

Inside the sub-class of the containing class.

Hence, protected internal acts like 'protected OR internal', i.e., either protected or internal.

The sealed keyword

Finally, if you don't want your class to be inherited by any class, you can mark it with the sealed keyword. No class can inherit from a sealed class.

sealed class A

{

...

88

Programmers Heaven: C# School

}

If one tries to inherit another class B with class A

class B : A

{

...

}

The compiler will generate the following error:

'CSharpSchool.B' : cannot inherit from sealed class 'CSharpSchool.A'

Author's Note: C#'s sealed keyword is identical to Java's final keyword when applied to classes.

Object class - the base of all classes

In C# (and the .NET framework) all the types (classes, structures and interfaces) are implicitly inherited from the Object class defined in the System namespace. This class provides the low-level services and general functionality to each and every class in the .NET framework. The Object class is extremely useful when it comes to polymorphism (which we are about to see), as a reference of type Object can hold any type of object. The Object class has following methods:

Method Name

Description

Equals(Object)

Compares two objects for equality. The default implementation only

 

supports reference equality, that is, it will return true if both

 

references point to the same object. For value types, bitwise checking

 

is performed. Derived classes should override this method to define

 

equality for their objects.

Static Equals(Object, Object)

Same as above except, this method is static.

GetHashCode()

Returns the hash code for the current object.

GetType()

Returns the Type object that represents the exact run-time type of the

 

current object.

static ReferenceEquals (Object,Object)

Returns true if both the references passed point to the same object,

 

otherwise returns false.

ToString()

Returns the string representation of the object. Derived classes should

 

override this method to provide the string representation of the current

 

object.

protected Finalize()

This protected method should be overridden by the derived classes to

 

free any resources. This method is called by CLR before the current

 

object is reclaimed by Garbage Collector.

protected MemberwiseClone()

Provides a shallow copy of the current object. A shallow copy

 

contains a copy of all the instance fields (state) of the current objects.

89

 

Programmers Heaven: C# School

C# also provides an object keyword which maps to the System.Object class in the .NET framework class library (FCL).

Polymorphism

It is said that a programmer goes through three stages when learning an object oriented programming language. e first phase is when a programmer uses non-object oriented constructs (like for, if...else, switch...case) of the object oriented programming language. The second phase is when a programmer writes classes, inherits them and creates their objects. The third phase is when a programmer uses polymorphism to achieve late binding.

MSDN (Microsoft Developer Network) explanation: "Polymorphism is the ability for classes to provide different implementations of methods that are called by the same name. Polymorphism allows a method of a class to be called without regard to what specific implementation it provides."

Using the reference of the base type for referencing the objects of child types

Before getting into the details of polymorphism, we need to understand that the reference of a base type can hold the object of a derived type. Let a class A be inherited by a class B:

class A

{

public void MethodA()

{

...

}

}

class B : A

{

public void MethodB()

{

...

}

}

Then it is legal to write:

A a = new B();

Here a reference of type A is holding an object of type B. In this case we are treating the object of type B as an object of type A (which is quite possible as B is a sub-type of A). Now, it is possible to write:

90

Соседние файлы в папке books