Inheritance

Inheritance is the idea that one class, called a subclass, can be based on another class, called a base class. Inheritance provides a mechanism for creating hierarchies of objects.
Inheritance is the ability to apply another class's interface and code to your own class.
Normal base classes may be instantiated themselves, or inherited. Derived classes can inherit base class members marked with protected or greater access. The derived class is specialized to provide more functionality, in addition to what its base class provides. Inheriting base class members in derived class is not mandatory.
Access Keywords
base -> Access the members of the base class.
this -> Refer to the current object for which a method is called.

The base keyword is used to access members of the base class from within a derived class:
Call a method on the base class that has been overridden by another method. Specify which base-class constructor should be called when creating instances of the derived class. A base class access is permitted only in a constructor, an instance method, or an instance property accessor.

In following example, both the base class, Person, and the derived class, Employee, have a method named Getinfo. By using the base keyword, it is possible to call the Getinfo method on the base class, from within the derived class.
// Accessing base class members
using System;public class Person
{
protected string ssn = "444-55-6666";protected string name = "John L. Malgraine";public virtual void GetInfo()
{
Console.WriteLine("Name: {0}", name);
Console.WriteLine("SSN: {0}", ssn);
}
}
class Employee: Person
{
public string id = "ABC567EFG";public override void GetInfo()
{
// Calling the base class GetInfo method:base.GetInfo();
Console.WriteLine("Employee ID: {0}", id);
}
}
class TestClass
{
public static void Main()
{
Employee E =
new Employee();
E.GetInfo();
}
}
Output
Name: John L. Malgraine
SSN: 444-55-6666
Employee ID: ABC567EFG

Base class constructors can be called from derived classes. To call a base class constructor, use the base() constructor reference. This is desirable when it's necessary to initialize a base class appropriately.
Here's an example that shows the derived class constructor with an address parameter:

abstract
public class Contact
{
private string address;public Contact(string b_address)
{
this.address = b_address;
}
}
public class Customer : Contact
{
public Customer(string c_address) : base(C_address)
{
}
}
In this code, the Customer class does not have an address, so it passes the parameter to its base class constructor by adding a colon and the base keyword with the parameter to its declaration. This calls the Contact constructor with the address parameter, where the address field in Contact is initialized.

One more example which shows how base-class constructor is called when creating instances of a derived class:
using System;public class MyBase
{
int num;public MyBase()
{
Console.WriteLine("In MyBase()");
}
public MyBase(int i)
{
num = i;
Console.WriteLine("in MyBase(int i)");
}
public int GetNum()
{
return num;
}
}
public class MyDerived : MyBase
{
static int i = 32;// This constructor will call MyBase.MyBase()public MyDerived(int ii) : base()
{
}
// This constructor will call MyBase.MyBase(int i)public MyDerived() : base(i)
{
}
public static void Main()
{
MyDerived md =
new MyDerived(); // calls public MyDerived() : base(i) and// passes i=32 in base classMyDerived md1 = new MyDerived(1); // call public MyDerived() : base(i)}
}
Output
in MyBase(int i)
in MyBase()

The following example will not compile. It illustrates the effects of not including a default constructor in a class definition:

abstract
public class Contact
{
private string address;public Contact(string address)
{
this.address = address;
}
}
public class Customer : Contact
{
public Customer(string address)
{
}
}
In this example, the Customer constructor does not call the base class constructor. This is obviously a bug, since the address field will never be initialized.

When a class has no explicit constructor, the system assigns a default constructor. The default constructor automatically calls a default or parameterless base constructor. Here's an example of automatic default constructor generation that would occur for the preceding example:
public Customer() : Contact()
{
}

When a class does not declare any constructors, the code in this example is automatically generated. The default base class constructor is called implicitly when no derived class constructors are defined. Once a derived class constructor is defined, whether or not it has parameters, a default constructor will not be automatically defined, as the preceding code showed.

Calling Base Class Members
Derived classes can access the members of their base class if those members have protected or greater access. Simply use the member name in the appropriate context, just as if that member were a part of the derived class itself. Here's an example:
abstract public class Contact
{
private string address;private string city;private string state;private string zip;public string FullAddress()
{
string fullAddress = address + '\n' + city + ',' + state + ' ' + zip;return fullAddress;
}
}
public class Customer : Contact
{
public string GenerateReport()
{
string fullAddress = FullAddress();// do some other stuff...return fullAddress;
}
}
In above example, the GenerateReport() method of the Customer class calls the FullAddress() method in its base class, Contact. All classes have full access to their own members without qualification. Qualification refers to using a class name with the dot operator to access a class member-MyObject.SomeMethod(), for instance. This shows that a derived class can access its base class members in the same manner as its own.

More Tips regarding Inheritance:
  • A static member cannot be marked as override, virtual, or abstract. So following is an error:
    public static virtual void GetSSN()
  • You can't call static methods of base class from derived class using base keyword.
    In above example if you declare a static method as follows:
public class Person
{
protected string ssn = "444-55-6666";protected string name = "John L. Malgraine";public static void GetInfo()
{
// Implementation}
}
now you can't call this method using base.GetInfo() from derived class instead you have to call Person.GetInfo() from derived class.
Inside Static members we can access only static fields, methods etc.
Following example will give error, because we can't access name in GetInfo() because name is not static.
public class Person
{
protected string ssn = "444-55-6666";protected string name = "John L. Malgraine";public static void GetInfo()
{
Console.WriteLine("Name: {0}", name);
Console.WriteLine("SSN: {0}", ssn);
}
}
Virtual or abstract members cannot be private.
  •  If you are not overriding a virtual method of base class in derived class, you can't use base class method by using base keyword in derived class. Also when you will create an instance of derived class, it will call derived class method and you will only be able to access base class method when you will create instance of base class.
  • You can't decrease access level of a method in derived class when you are overriding a base class method in derived class, vice versa is possible.
    Means you can make protected method of base class to public in derived class.
The "this" keyword refers to:
  • the current instance for which a method is called. Static member functions do not have a this pointer. The this keyword can be used to access members from within constructors, instance methods, and instance accessors.
    The following are common uses of this:
To qualify members hidden by similar names, for example:
public Employee(string name, string alias)
{
this.name = name;this.alias = alias;
}
In above example, this.name refers to private variable name in the class. If we write name = name, then this will refer to argument name of the constructor Employee and not to private variable name in the class. In this case private variable name will never be initialized.
  • To pass an object as a parameter to other methods, for example:
    CalcTax(this);
To declare indexers, for example:

public int this [int param]
{
get{return array[param];
}
set{
array[param] =
value;
}
}
It is an error to refer to this in a static method, static property accessor, or variable initializer of a field declaration.
In this example, this is used to qualify the Employee class members, name and alias, which are hidden by similar names. It is also used to pass an object to the method CalcTax, which belongs to another class.
// keywords_this.cs
// this example
using System;public class Employee
{
public string name;public string alias;public decimal salary = 3000.00m;// Constructor:public Employee(string name, string alias)
{
// Use this to qualify the fields, name and alias:this.name = name;this.alias = alias;
}
// Printing method:public void printEmployee()
{
Console.WriteLine("Name: {0}\nAlias: {1}", name, alias);
// Passing the object to the CalcTax method by using this:Console.WriteLine("Taxes: {0:C}", Tax.CalcTax(this));
}
}
public class Tax
{
public static decimal CalcTax(Employee E)
{
return (0.08m*(E.salary));
}
}
public class MainClass
{
public static void Main()
{
// Create objects:Employee E1 = new Employee ("John M. Trainer", "jtrainer");// Display results:E1.printEmployee();
}
}
Output
Name: John M. Trainer
Alias: jtrainer
Taxes: $240.00
Category: , 0 comments

Leave a comment