base and name hiding
In this chapter you will learn:
- A demo showing what is name hiding
- How to use base to reference parent class
- How to call a hiddel method from parent class
What is name hiding
An example of inheritance-related name hiding.
using System; //j av a 2s. c om
class BaseClass {
public int i = 0;
}
// Create a derived class.
class DerivedClass : BaseClass {
new int i; // this i hides the i in BaseClass
public DerivedClass(int b) {
i = b; // i in DerivedClass
}
public void show() {
Console.WriteLine("i in derived class: " + i);
}
}
class MainClass {
public static void Main() {
DerivedClass ob = new DerivedClass(2);
ob.show();
}
}
The code above generates the following result.
Use base to reference member from parent class
The following code shows to how to use base to overcome name hiding.
using System; // j a v a 2s. c om
class BaseClass {
public int i = 0;
}
// Create a derived class.
class DerivedClass : BaseClass {
new int i; // this i hides the i in BaseClass
public DerivedClass(int a, int b) {
base.i = a; // this uncovers the i in BaseClass
i = b; // i in DerivedClass
}
public void show() {
// this displays the i in BaseClass.
Console.WriteLine("i in base class: " + base.i);
// this displays the i in DerivedClass
Console.WriteLine("i in derived class: " + i);
}
}
class MainClass {
public static void Main() {
DerivedClass ob = new DerivedClass(1, 2);
ob.show();
}
}
The code above generates the following result.
Call a hidden method from parent class
using System; //from j a va 2s.c o m
class BaseClass {
public int i = 0;
// show() in BaseClass
public void show() {
Console.WriteLine("i in base class: " + i);
}
}
// Create a derived class.
class DerivedClass : BaseClass {
new int i; // this i hides the i in BaseClass
public DerivedClass(int a, int b) {
base.i = a; // this uncovers the i in BaseClass
i = b; // i in DerivedClass
}
// This hides show() in BaseClass. Notice the use of new.
new public void show() {
base.show(); // this calls show() in BaseClass
// this displays the i in DerivedClass
Console.WriteLine("i in derived class: " + i);
}
}
class MainClass {
public static void Main() {
DerivedClass ob = new DerivedClass(1, 2);
ob.show();
}
}
The code above generates the following result.
Next chapter...
What you will learn in the next chapter:
- Get to know C#'s Access Specifiers
- Matrix showing the usage of access modifiers
- A demo showing how to use access modifiers
Home » C# Tutorial » Class