6.5 Class inheritance
Inheritance in C# works in very much the same way as in Java, except for some differences in method overriding (see section 7.10). A class can inherit from only one superclass, and can implement multiple interfaces. Note the syntactical differences between the two languages though.
To inherit one class from another, use the following syntax:
class <class_name>:<super_class>
The code below contains two classes, Child and Parent. Child is a subclass of Parent, and inherits the DoSomething() method.
1: using System;
2:
3: public class Parent{
4: protected void DoSomething(){
5: Console.WriteLine("inherited from Parent ");
6: }
7: }
8: public class Child:Parent{
9: static public void Main (){
10: new Child().DoSomething();
11: }
12: }
Output:
c:\expt>test
inherited from Parent
Like Java
Every C# class must have one (and only one) superclass, except for System.Object which has no superclass. If no superclass is specified, a C# class implicitly subclasses System.Object directly. All class members are inherited except private members, constructors (both instance constructors and static constructors), and the special C# destructors. Multiple class inheritance is not supported. You should look at implementing multiple interfaces as a rough substitute for multiple class inheritance.
Unlike Java
C# has a keyword virtual which is not found in Java. Methods, properties, and indexers can be declared virtual if they are intended to be overridden in subclasses. Only methods, properties, and indexers are class members whose implementation can be overridden in subclasses. (See section 7.7 for more information on virtual methods.) The direct superclass of a class type must be at least as accessible as the class type itself. For example, the following two line C# file does not compile:
1: public class Child:Parent{}
2: class Parent{}
The compilation error given is:
test.cs(1,14): error CS0060: Inconsistent accessibility: base class 'Parent' is less
accessible than class 'Child'
Java does not have this requirement. The following Java file compiles properly:
1: public class Child extends Parent{}
2: class Parent{}
Additional note
The direct superclass of a user-defined class type must not be any of the following types:
System.Array System.Delegate System.Enum System.ValueType
These are special classes of the BCL.
 |