CSharp examples for Custom Type:Inheritance
To inherit from a class, you use this format:
class derived_class : base_class
The colon ( :) is used to indicate inheritance by separating the new, derived_class, from the original, base_class.
using System;/* ww w . j a va 2s. co m*/ using System.Text; class Person { protected string firstName; protected string middleName; protected string lastName; private int age; public Person() { } public Person(string fn, string ln) { firstName = fn; lastName = ln; } public Person(string fn, string mn, string ln) { firstName = fn; middleName = mn; lastName = ln; } public Person(string fn, string mn, string ln, int a) { firstName = fn; middleName = mn; lastName = ln; age = a; } public void displayAge() { Console.WriteLine("Age {0}", age); } public void displayFullName() { StringBuilder FullName = new StringBuilder(); FullName.Append(firstName); FullName.Append(" "); if (middleName != "") { FullName.Append(middleName[0]); FullName.Append(". "); } FullName.Append(lastName); Console.WriteLine(FullName); } } class Employee : Person { private ushort hYear; public ushort hireYear { get { return (hYear); } set { hYear = value; } } public Employee() : base() { } public Employee(string fn, string ln) : base(fn, ln) { } public Employee(string fn, string mn, string ln, int a) : base(fn, mn, ln, a) { } public Employee(string fn, string ln, ushort hy) : base(fn, ln) { hireYear = hy; } public new void displayFullName() { Console.WriteLine("Employee: {0} {1} {2}", firstName, middleName, lastName); } } class NameApp { public static void Main() { Person myWife = new Person("A", "A", "J", 21); Employee me = new Employee("B", "L", "J", 23); Employee you = new Employee("K", "R", 2000); myWife.displayFullName(); myWife.displayAge(); me.displayFullName(); Console.WriteLine("Year hired: {0}", me.hireYear); me.displayAge(); you.displayFullName(); Console.WriteLine("Year hired of him: {0}", you.hireYear); you.displayAge(); } }