Inheritance & Access Modifiers


Inheritance and Access Modifiers


A derived class inherits every thing from the base class except constructors and destructors. The public members of the Base class becomes the public members of the Derived class also. Similarly the protected members of the base class become protected members of the derived class and internal member becomes internal members of the derived class. Even the private members of the base class are inherited to the derived class, even though derived class can't access them.

Inheritance and Data Members


We know all base class data members are inherited to the derived, but their accessibility remains unchanged in the derived class. For example in the program given below


using System; 
class Base 
{ 
public int x = 10; 
public int y = 20; 
} 
class Derived : Base 
{ 
public int z = 30; 
public void Sum() 
{ 
int sum = x+y+z; 
Console.WriteLine(sum); 
} 
} 
class MyClient 
{ 
public static void Main() 
{ 
Derived d1 = new Derived(); 
d1.Sum();// displays '60' 
} 
}   


Here class Derived have total three data members, two of them are inherited from the Base class.

In C#, even it is possible to declare a data member with the same name in the derived class as shown below. In this case, we are actually hiding a base class data member inside the Derived class. Remember that, still the Derived class can access the base class data member by using the keyword base .


using System; 
class Base 
{ 
public int x = 10; 
public int y = 20; 
} 
class Derived : Base 
{ 
public int x = 30; 
public void Sum() 
{ 
int sum = base.x+y+x; 
Console.WriteLine(sum); 
} 
} 
class MyClient 
{ 
public static void Main() 
{ 
Derived d1 = new Derived(); 
d1.Sum();// displays '60' 
} 
}    


But when we compile the above program, the compiler will show a warning, since we try to hide a Base class data member inside the Derived class. By using the keyword new along with the data member declaration inside the Derived class, it is possible to suppress this compiler warning. The keyword new tells the compiler that we are trying to explicitly hiding the Base class data member inside the Derived class. Remember that we are not changing the value of the Base class data member here. Instead we are just hiding or shadowing them inside the Derived class. However the Derived class can access the base class data member by using the base operator.



using System; 
class Base 
{ 
public int x = 10; 
public int y = 20; 
} 
class Derived : Base 
{ 
public new int x = 30; 
public void Sum() 
{ 
int sum = base.x+y+x; 
Console.WriteLine(sum); 
} 
} 
class MyClient 
{ 
public static void Main() 
{ 
Derived d1 = new Derived(); 
d1.Sum();// displays '60' 
} 
}    
Category: , 0 comments

Leave a comment